- Two Sum
- 3Sum
- 3Sum Closest
Two Sum
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法一
一下能想到的思路就是内外两个循环找和为target的两个数字,这样的复杂度是O(n*n)。
解法二
想到能否用哈希表,每遍历到一个元素num,看target-num是否在hash表中,如果在就得出答案,如果不在就将当前num放入哈希表中。
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map= new HashMap<Integer,Integer>();
int[] result = new int[2];
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
result[0]=i;
result[1] = map.get(target-nums[i]);
break;
}