这题让我们在数组中找到两个数,使它们的和为target,并返回数组下标。
第一想到的是暴力搜索法,结果很失望也预料之中,运行超时。
于是我们需要换个方法,因为HashMap是常数级的查找,因此我们想到了使用它来建立映射关系并便于查找。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] two = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for(int j = 0 ;j < nums.length ;j++) {
int k = target - nums[j];
if(map.containsKey(k) && map.get(k)!=j) {
two[0] = nums[j];
two[1] = map.get(k);
}
}
return two;
}
}