[LeetCode] Two Sum

来源:互联网 发布:ubuntu install g 编辑:程序博客网 时间:2024/05/01 03:52

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

这题第二次做,结果一下还没成功,比较二的自作聪明的写了if(numbers[i]>target) continue;

其实这样一来就打破了map里原数组的顺序, e.g [-3.4,3,90] target=0 的test case中就出错了。

还有就是map.put()的时机,e.g. [3,4,2,7] target=6, 我最开始是直接在for循环里初始就map.put(numbers[i],i)了。这样在后面的判断就成功了,于是

返回了两个[1,1], 而不是[2,3]. 后来还在考虑index大小的问题。

e.g. [0,4,3,0] 如果我们一开始就put进去,那么到第二个0的时候,map中的value是[0=4,4=2,3=3] 就覆盖掉之前的结果了. 所以最好是先判断,再存入.


    public int[] twoSum(int[] numbers, int target) {        int[] res=new int[2];        if(numbers.length==0) return res;        HashMap<Integer, Integer> map= new HashMap<>();        for(int i=0;i<numbers.length;i++){             if(map.containsKey(target-numbers[i])){                res[0]=map.get(target-numbers[i])+1;                res[1]=i+1;                return res;            }                map.put(numbers[i],i);        }        return res;    }


0 0