【题目】
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
【示例】
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
【代码】
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> m;
map<int,int> k;
vector<int> rs;
int cnt=0;
for(int i=0;i<nums.size();i++){
if(m[nums[i]])
k[nums[i]]=i+1;
else
m[nums[i]]=i+1;
}
for(auto x:m){
if(m[target-x.first]){
rs.push_back(x.second-1);
if(target-x.first==x.first)
rs.push_back(k[target-x.first]-1);
else
rs.push_back(m[target-x.first]-1);
return rs;
}
cnt++;
}
return rs;
}
};
【高效】
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};

本文介绍了一种解决“两数之和”问题的有效算法。给定一个整数数组及目标值,在数组中寻找两数之和等于目标值的元素,并返回其下标。文章提供了两种实现方式,一种使用了标准的映射表,另一种则采用了哈希表来提高查找效率。

被折叠的 条评论
为什么被折叠?



