LeetCode-1-两数之和
程序员文章站
2022-03-06 08:20:53
...
题目链接:https://leetcode-cn.com/problems/two-sum/
方法:利用unordered_map哈希查找,先建立哈希表O(n),再查找O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>result;
int d;
unordered_map<int, int>unomap; //标准库哈希表容器
for (int i = 0; i < nums.size(); ++i)
{
unomap[nums[i]] = i; //将值存为key 下标存为value
}
for (int i = 0; i < nums.size(); ++i)
{
d = target - nums[i];
if (unomap.find(d) != unomap.end() && unomap[d] > i)
{
result.push_back(i);
result.push_back(unomap[d]);
break;
}
}
return result;
}
};