Skip to content

Commit 5221fa1

Browse files
authored
Update TwoSum solution to use hashmap to remove nested loop
1 parent 2046988 commit 5221fa1

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

TwoSum/solution.cpp

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
11
class Solution {
22
public:
33
vector<int> twoSum(vector<int>& nums, int target) {
4+
unordered_map<int, int> hashmap;
5+
46
for (int i=0; i<nums.size(); i++)
57
{
6-
for (int j=0; j<nums.size(); j++)
7-
{
8-
// Cannot use same element twice
9-
if (i == j)
10-
{
11-
continue;
12-
}
8+
int curNum = nums.at(i);
9+
int neededNum = target - curNum;
10+
11+
// check if needed value exists already in the hashmap
12+
// return the indices of both value if it does
13+
if (hashmap.count(neededNum) != 0)
14+
return {i, hashmap[neededNum]};
1315

14-
// Check sum
15-
if (nums.at(i) + nums.at(j) == target)
16-
{
17-
return {i, j};
18-
}
19-
}
16+
// add current value mapped to current index to hashmap sp it can be queried later
17+
hashmap[curNum] = i;
2018
}
2119

2220
// Should never reach here because one solution is guaranteed

0 commit comments

Comments
 (0)