1,题目要求
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, and you may not use the same element twice.
给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。
您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。
2,题目思路
对于这道题,是比较特殊的一道题,它是LeetCode上的第一道题,应该也是做得人最多的一道题了,足足有380万个submission,fucking crazy!
一个比较常见的思路,是直接进行穷举,这样虽然可行,但是时间复杂度会达到O(n2),非常的不好。
对题目进行观察我们可以得知,题目是找出数组中的两个数,使得他们之和为给定的值。于是,思路便是,我们可以在遍历数组的过程中,判断 target - nums[i] 是否在我们所定义的容器中,如果在,就说明我们找到了对应的组合。此时直接break即可。
如果不在,则将该数字加入到我们的容器中,继续进行下一次的遍历。
对于这点,因为其中涉及到数字的值以及其对应的索引,同时我们更关注与查找到这个数字而非得到一个有序序列,因此,为了提高查找效率,我们使用unordered_map来作为我们的容器。
3,代码实现
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.size() == 0)
return {};
unordered_map<int,int> hashMap = {};
vector<int> res = {};
for(int i = 0;i<nums.size();i++){
if(hashMap.find(target - nums[i])!=hashMap.end()){
res.push_back(hashMap[target-nums[i]]);
res.push_back(i);
break;
}
else
hashMap[nums[i]] = i;
}
return res;
}
};
- python解法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
res = []
# 构造一个字典,其中key为对应的数字的值,便于快速定位;value则为index,方便找到对应值在nums中的位置
hash_map_dict = {}
for index, value in enumerate(nums):
another_number = target - value
if another_number in hash_map_dict:
return [index, hash_map_dict[another_number]]
hash_map_dict[value] = index
return []