-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo-sum.cpp
More file actions
31 lines (27 loc) · 737 Bytes
/
two-sum.cpp
File metadata and controls
31 lines (27 loc) · 737 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
27
28
29
30
31
// 1. Two Sum (2/9/56554)
// Runtime: 7 ms (72.72%) Memory: 14.36 MB (14.74%)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
// key missing operand
// value index of the missing operand
std::unordered_map<int, int> diffs;
std::vector<int> indeces;
for (int i = 0; i < nums.size(); i++)
{
const auto diff = target - nums[i];
if (diffs.find(diff) != diffs.end())
{
indeces.push_back(diffs[diff]);
indeces.push_back(i);
break;
}
else
{
diffs[nums[i]] = i;
}
}
return indeces;
}
};