Skip to content

Commit 662e8bc

Browse files
Merge pull request #5 from AshishKumar077/patch-1
Create 2 sum solution
2 parents 0831dfe + b800377 commit 662e8bc

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

2 sum solution

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
vector<int> twoSum(vector<int>& nums, int target)
4+
{
5+
int size = nums.size();
6+
7+
// x, target-x -> add to target.
8+
9+
map<int, int> pos_map;
10+
11+
for(int i=0; i<size;i++)
12+
{
13+
int curr_num = nums[i];
14+
15+
int to_find = target-curr_num;
16+
17+
if (pos_map[to_find]!=0)
18+
{
19+
// currnum + to_find = target
20+
return vector<int>{i, pos_map[to_find]-1};
21+
22+
}
23+
24+
pos_map[curr_num] = i+1;
25+
// done :)
26+
27+
}
28+
29+
return vector<int>{-1,-1};
30+
}

0 commit comments

Comments
 (0)