两数之和
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
查找的问题,先想hash。
C++版
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashMap;
for (int i = 0; i < nums.size(); i++) hashMap[nums[i]] = i;
for (int i = 0; i < nums.size(); i++) {
if (hashMap.count(target - nums[i]) != 0
&& i != hashMap[target - nums[i]])
return {i, hashMap[target - nums[i]]};
}
return {};
}
Java版:
先比较后put 会不会忽略掉最后一个元素呢? 比如: 1 2 3 5 target=6
当然不会 因为在put 5 之前 已经查找了6-5 是不是在map里面
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
int sub = target - nums[i];
if (hashMap.containsKey(sub))
return new int[]{hashMap.get(sub), i};
hashMap.put(nums[i], i);
}
return new int[0];
}