class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> two;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); i++) {
m.insert(pair<int, int>(nums[i], i));
}
unordered_map<int, int>::iterator it;
for (int i = 0; i < nums.size(); i++) {
if ((it = m.find(target - nums[i])) != m.end() && it->second != i) {
int first = min(i, it->second);
int second = max(i, it->second);
two.push_back(first);
two.push_back(second);
return two;
}
}
}
};
LetCode 1.两数之和
最新推荐文章于 2025-04-22 15:59:52 发布
本文介绍了一种解决两数之和问题的高效算法实现。通过使用哈希表(unordered_map),该算法能在O(n)的时间复杂度内找到数组中两个数相加等于特定目标值的下标。
949

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



