1. Two Sum

需要注意的问题:

1. 这个数组有没有重复的数字

2. 这个数组有没有排序过

 

建一个hashmap, 但是不能直接把数字放进去,再一个个查,因为会有以下的问题:

1. 如果给定的数组是[3,2,5,6],target = 6. 这个时候输出出的结果会是[1,1].

2. 如果给定的数组是[2,2,5,6], target = 4. 那先放进去的结果是少了一个2

所以要放进去之前看一看map里面有没有目标数字,如果有的话,就输出结果,如果没有的话,就把这个数字放进去。

即使出现重复的数字也不要紧,因为:

1.这道题是2sum,如果出现重复数字并且重复数字可以达到target目标,那么再放入前就已经检出;

2. 如果该数字可以和后面的某个数字组成target,那么留一个也就够了不需要两个

 

所以代码如下:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            int rest = target - nums[i];
            if(!map.containsKey(rest)) {
                map.put(nums[i], i);
            } else {
                int index = map.get(rest);
                res[0] = Math.min(i, index) + 1;
                res[1] = Math.max(i, index) + 1;
            }
        }
        return res;
    }
}

这道题的时间复杂度是O(n)

posted @ 2016-01-03 15:42  warmland  阅读(94)  评论(0编辑  收藏  举报