File tree Expand file tree Collapse file tree 1 file changed +11
-13
lines changed Expand file tree Collapse file tree 1 file changed +11
-13
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public:
3
3
vector<int > twoSum (vector<int >& nums, int target) {
4
+ unordered_map<int , int > hashmap;
5
+
4
6
for (int i=0 ; i<nums.size (); i++)
5
7
{
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]};
13
15
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;
20
18
}
21
19
22
20
// Should never reach here because one solution is guaranteed
You can’t perform that action at this time.
0 commit comments