Skip to content

Commit dd27809

Browse files
authored
Update 0001-two-sum.cpp
My solution resembles more like shown in neetcode video and also has better runtime
1 parent 9dda2be commit dd27809

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

cpp/0001-two-sum.cpp

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,16 @@
1111
class Solution {
1212
public:
1313
vector<int> twoSum(vector<int>& nums, int target) {
14-
unordered_map<int, int> m;
15-
vector<int> result;
16-
17-
for (int i = 0; i < nums.size(); i++) {
18-
int complement = target - nums[i];
19-
if (m.find(complement) != m.end()) {
20-
result.push_back(m[complement]);
21-
result.push_back(i);
22-
break;
23-
} else {
24-
m.insert({nums[i], i});
14+
int n = nums.size();
15+
unordered_map<int, int> mp; // val -> index
16+
17+
for (int i = 0; i < n; i++) {
18+
int compliment = target - nums[i];
19+
if (mp.find(compliment) != mp.end()) {
20+
return {mp[compliment], i};
2521
}
22+
mp.insert({nums[i], i});
2623
}
27-
28-
return result;
24+
return {};
2925
}
3026
};

0 commit comments

Comments
 (0)