问题描述:
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
方法两种:一种是暴力搜索,也能通过,时间复杂度是O(n2),空间复杂度为O(1),一种使用hash表,时间复杂度为O(n),空间复杂度为O(n)。
hash做法:356 ms
public int[] twoSum(int[] nums, int target){
int[] res = new int[2];
//使用hashMap:key:nums[i]=>value:i
HashMap maps = new HashMap();
for(int i = 0;i
maps.put(nums[i], i);
}
for(int i = 0;i
int remain = target-nums[i];
if(maps.containsKey(remain)){
int index1 = i+1;
int index2 = maps.get(remain)+1;
if(index1==index2)
continue;
res[0] = index1
res[1] = index1>index2?index1:index2;
break;
}
}
return res;
}