forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
26 lines (24 loc) · 799 Bytes
/
solution.cpp
File metadata and controls
26 lines (24 loc) · 799 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
// 使用哈希表存储数组中的数值,key为数组中的数值,value为数组中数值对应下标
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++)
{
int numberToFind = target - numbers[i];
// 查找,若找到,则返回下标
if (hash.find(numberToFind) != hash.end())
{
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
//若没有找到,则将该值加入哈希表
hash[numbers[i]] = i;
}
return result;
}
};