Skip to content

Commit e4b16b1

Browse files
committed
adding two sum
1 parent 1a005dc commit e4b16b1

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/cpp/SomaDoisNumeros.cpp

+42
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)