找到一个数组中其中两个数的和为目标值的组合,并返回索引值。最直接的想法就是遍历数组,就可以找到该组合,但是此时的复杂度为O(n2)。那么就要用空间来换取时间。其中HashMap的查找速度是最快的。
因此,首先需要遍历一次数组,把每个数与其索引值对应的存储到Map当中。然后再遍历一次数组,此时要找寻的新目标值为target-nums[i]。在map中查找,判断是否存在。这样时间复杂度只为O(n)。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] res = new int[2];
for(int i = 0;i < nums.length;i++){
map.put(nums[i],i);
}
for(int i = 0;i < nums.length;i++){
int t = target - nums[i];
if(map.containsKey(t) && map.get(t)!=i){
res[0] = i;
res[1] = map.get(t);
break;
}
}
return res;
}
}