[LeetCode]1. Two Sum
题目描述
思路
题目给出的数组包含重复元素,并且无序
考虑使用hash
初始化一个空的hash
遍历数组
对于每个数nums[i], 计算互补的数 target - nums[i]
在hash中查找这个互补的数,若不存在,则将nums[i]和i对应存入hash中
若存在,在保存到数组中,返回
代码
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i){
if (m.count(target - nums[i])) {
res.push_back(m[target - nums[i]]);
res.push_back(i);
break;
}
else {
m[nums[i]] = i;
}
}
return res;
}
};
int main() {
vector<int> nums = { 3, 3 }, res;
int target = 6;
Solution s;
res = s.twoSum(nums, target);
for (int p : res)
cout << p << " ";
cout << endl;
system("pause");
return 0;
}
本文介绍了解决LeetCode经典题目“两数之和”的高效算法。通过使用哈希表,可以在O(n)的时间复杂度内找到数组中两个数相加等于特定目标值的下标,适用于包含重复元素的无序数组。
689

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



