Skip to content

Commit 85ff76c

Browse files
authored
Merge pull request kelvins#239 from Riei-Joaquim/feat/two_sum_cpp
Feat/two sum cpp
2 parents 28d638c + e745fd4 commit 85ff76c

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3442,8 +3442,8 @@ Com o objetivo de alcançar uma abrangência maior e encorajar mais pessoas a co
34423442
</a>
34433443
</td>
34443444
<td> <!-- C++ -->
3445-
<a href="./CONTRIBUTING.md">
3446-
<img align="center" height="25" src="./logos/github.svg" />
3445+
<a href="./src/cpp/TwoSum.cpp">
3446+
<img align="center" height="25" src="./logos/cplusplus.svg" />
34473447
</a>
34483448
</td>
34493449
<td> <!-- Java -->

src/cpp/TwoSum.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <unordered_map>
3+
#include <vector>
4+
5+
/*!
6+
* \brief Determine whether in the list of retrieved numbers there is a
7+
combination of two numbers that resulted in the target sum.
8+
* \return Two indexes of the list whose sum of elements results in the
9+
target value
10+
*/
11+
std::vector<int> twoSum(std::vector<int> &nums, int target) {
12+
std::unordered_map<int, int> mapSum; // val, vect<idx>
13+
14+
for (int i = 0; i < nums.size(); i++) {
15+
int compTarget = target - nums[i];
16+
17+
if (mapSum.count(compTarget)) {
18+
return {i, mapSum[compTarget]};
19+
} else {
20+
mapSum.insert({nums[i], i});
21+
}
22+
}
23+
24+
return {};
25+
}
26+
27+
int main() {
28+
std::vector<int> values{9, 1, 2, 5, 7, 11, 15};
29+
int target = 9;
30+
31+
auto sumIdxFor = twoSum(values, target);
32+
if (sumIdxFor.empty()) {
33+
std::cout << "no existent values with two sum: " << target << " in array"
34+
<< std::endl;
35+
} else {
36+
std::cout << "Two sum for target: " << target << " in array is "
37+
<< values[sumIdxFor[0]] << " and " << values[sumIdxFor[1]]
38+
<< std::endl;
39+
}
40+
41+
return 0;
42+
}

0 commit comments

Comments
 (0)