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
【算法思路】
1. 暴力搜索,对于每个数 i,在剩下的数组元素中寻找target - i。 时间复杂度 O(n^2)
2. 遍历数组,往hashmap中插入每个数 i 对应的另一个元素target - i (key)及其下标(value)。
当发现某个key已经存在于map中时,说明该数与之前的一个数之和为target,那么找到了对应的index。
【复杂度】
时间 :O(n) 一次遍历
空间 O(n) Hashmap
ps: 严格来说,target-numbers[i]可能溢出int,因此提升为long更鲁棒。
【CODE】
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] index = new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < len; i ++)
{
if(!map.containsKey(nums[i]))
{
map.put(target - nums[i] , i);
}
else
{
index[0] = map.get(nums[i]) + 1;
index[1] = i + 1;
break;
}
}
return index;
}