題目描述:
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].
我的解答:
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] result = new int[2];
int num = nums.length;
for(int i=0;i<num;i++){
if(map.containsKey(nums[i])){
int index = map.get(nums[i]);
result[0] = index;
result[1] = i;
}else{
map.put(target-nums[i], i);
}
}
return result;
}
分析:
- 一開始嘗試使用循環遍歷的方法,雖然很容易想到,但是測試未通過,原因是時間復雜度為O(N^2)。參考了下網上的解法,主要思路是通過一個HashMap來實現,map里存放的鍵值對是(target-nums[index],index),從i=0開始去查找map里面是否存在nums[i],如果不存在,就把(target-nums[i],i)放入map,這樣如果查找到這個值,說明在之前有匹配的數,而且之前存入的index號是互補數的index。