Skip to content

1. Two Sum

Jacky Zhang edited this page Jul 28, 2016 · 2 revisions

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

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

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Array类题目

如果取nums中的一个值,每次都搜索一遍数组,时间复杂度为O(n^2),效率太低。 因此可以考虑采用HashMap,以数组的值为key,数组的下标为value,这样每次查找的就是HashMap的key值。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i]) && i != map.get(target - nums[i])) {
                int[] ans = new int[2];
                ans[0] = i;
                ans[1] = map.get(target - nums[i]);
                return ans;
            }
        }
        throw new IllegalArgumentException("No solution");
    }
}

可以看到需要scan数组nums两次,其实可以只扫描一次,在扫描的过程中查找是否存在answer。 因为在将后面的值添加进map前,可以查找前面已经存在的<k,v>中是否存在answer,若有,则直接返回答案。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i]) && i != map.get(target - nums[i])) {
                int[] ans = new int[2];
                ans[0] = i;
                ans[1] = map.get(target - nums[i]);
                return ans;
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No solution");
    }
}
Clone this wiki locally