Skip to content

Commit def8905

Browse files
Added solution
1 parent 433da3c commit def8905

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

two_sum_ii.cpp

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
vector<int> twoSum(vector<int>& numbers, int target) {
4+
unordered_map<int, int> mp;
5+
vector<int> solution(2, 0);
6+
7+
//store difference as first element of map and index as second element of map
8+
for(int i=0; i<numbers.size(); i++){
9+
int difference = target - numbers[i];
10+
auto it = mp.find(difference);
11+
12+
//elements not in map
13+
if(it != mp.end()){
14+
if(mp[difference] < i){
15+
solution[0] = mp[difference] + 1;
16+
solution[1] = i + 1;
17+
return solution;
18+
}
19+
}
20+
else
21+
mp[numbers[i]] = i;
22+
23+
}
24+
return vector<int>(2, 0);
25+
}
26+
};

0 commit comments

Comments
 (0)