给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用

476 阅读1分钟

public class Solution {
    public static void main(String[] args) {
        int[] num = {2, 7, 11, 15};
        int[] ints = twoSum(num, 9);
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }
    }

    public static int[] twoSum(int[] nums, int target) {
        int[] postions = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int j = 0; j < nums.length; j++) {
            int anotherValue = target - nums[j];
            if (map.containsKey(anotherValue) && map.get(anotherValue) != j) {
                int anotherPos = map.get(anotherValue);
                postions[0] = j;
                postions[1] = anotherPos;
                break;
            }
        }
        return postions;
    }
}