题目:
代码(首刷看解析 2024年1月15日):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int another = 0;
unordered_map<int,int> hash;
for(int i = 0; i < nums.size(); ++i) {
another = target - nums[i];
if(hash.find(another) != hash.end()) return {i,hash[another]};
else hash.emplace(nums[i],i);
}
return {0,0};
}
};
一开始做的时候把所有的数先存进hash表里再去找,结果这种情况无法满足重复key值,用multimap又无法检索键对应的值,最后看了代码随想录里的思路发现在遍历过程中插入即可。
代码(二刷自解 2024年3月2日 7min)
开始hot一百刷题之旅
class Solution {
public:
// 哈希
vector<int> twoSum(vector<int>& nums, int target) {
// 条件判断
if (nums.size() < 2) return vector<int>{0, 1};
// hash存储 value:index
unordered_map<int, int> hash;
// 遍历取哈希
for (int i = 0; i < nums.size(); ++i) {
if (hash.find(target - nums[i]) != hash.end()) {
return vector<int>{i, hash[target - nums[i]]};
} else {
hash.insert(pair<int,int>(nums[i], i));
}
}
return vector<int>{0, 1};
}
};
代码(三刷自解,2024年4月23日 bugfree)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// hash存下标,每次遍历的时候往里面存
unordered_map<int, int> value_to_index;
for (int i = 0; i < nums.size(); i++) {
// 先检测是否存在
if (value_to_index.find(target - nums[i]) != value_to_index.end()) {
return {value_to_index[target - nums[i]], i};
} else {
value_to_index[nums[i]] = i;
}
}
return {-1,-1};
}
};