Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 01218f4

Browse files
Add C++ solution to two sum problem
1 parent 150cbbc commit 01218f4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎c++_solutions/0001_two_sum.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <stdio.h>
2+
#include <utility>
3+
#include <unordered_map>
4+
#include <vector>
5+
#include <string>
6+
7+
class Solution {
8+
public:
9+
std::vector<int> twoSum(std::vector<int>& nums, int target) {
10+
// key: target - encountered num, value: index of encountered num
11+
std::unordered_map<int, int> num_pos;
12+
int num_items = nums.size();
13+
14+
for (int i=0; i < num_items; i++) {
15+
int curr_num = nums[i];
16+
// If the current number is not in the map
17+
if (num_pos.count(curr_num) == 0) {
18+
int sec_num = target-curr_num;
19+
num_pos.insert(std::make_pair(sec_num, i));
20+
}
21+
// If the current number is in the map, you found the answer
22+
else {
23+
return {num_pos[curr_num], i};
24+
}
25+
}
26+
27+
// If we go through the entire for loop without returning the answer
28+
// it means there was no valid pair
29+
return std::vector<int>();
30+
}
31+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /