two sum

2017-02-09  本文已影响13人  ibyr
Question

Given an array of integer, return indices of the two numbers such that they add up to a specific target.

Note
Extension
Solution
public int[]  twoSum(int[] nums, int target) {
    int[] res = new int[2];
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(target - nums[i])) {
            res[1] = i;
            res[0] = map.get(target - nums[i]);
        } else {
            map.put(nums[i], i);
        }
    }
    return res;
}
上一篇下一篇

猜你喜欢

热点阅读