题目描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例1:
输入:nums = [2,7,11,15], target = 9输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]
示例2:
输入:nums = [3,2,4], target = 6 输出:[1,2]
示例3:
输入:nums = [3,3], target = 6 输出:[0,1]
思路
错误思路
遍历数组,放入哈希表中,key是值,value是下标;
再次遍历数组,看target - nums[i]的值是否在哈希表中,在的话就返回。
错误原因:
如果nums = [3, 2, 4], target = 6, 那么会得到[0, 0]这种结果; 第一个3被用了两次。
暴力解法
即不断遍历,两层for循环,但是时间复杂度为O(n^2)
利用哈希表
哈希表的查找效率为O(1), 遍历数组, 设当前值为currentValue, 去哈希表里找是否存在sum - currentValue的key,如果有点话,就返回当前的索引和sum - currentValue的索引,否则就添加到哈希表中,哈希表的key是currentValue, 值是索引。
哈希表代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int currentValue = nums[i];
int difference = target - currentValue;
if (map.containsKey(difference)) {
result[0] = i;
result[1] = map.get(difference);
return result;
} else {
map.put(currentValue, i);
}
}
return result;
}
}