Skip to content

Commit 207a127

Browse files
committed
Create two-sum.cpp
1 parent 59b3929 commit 207a127

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

C++/two-sum.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> twoSum(vector<int>& nums, int target) {
7+
vector<int> res;
8+
unordered_map<int, int> lookup;
9+
for (int i = 0; i < nums.size(); ++i) {
10+
if (lookup.count(target - nums[i])) {
11+
res = {lookup[target - nums[i]], i};
12+
break;
13+
}
14+
lookup[nums[i]] = i;
15+
}
16+
return res;
17+
}
18+
};

0 commit comments

Comments
 (0)