Skip to content

Commit 28b138d

Browse files
Merge pull request matthewsamuel95#261 from zetef/master
Triplet sum
2 parents c388bcd + 9cb7449 commit 28b138d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Math/3Sum/3Sum.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <iostream>
2+
#include <algorithm>
3+
#include <unordered_map>
4+
5+
using namespace std;
6+
7+
bool find_triplet( int arr[], int arr_size, int value ) {
8+
unordered_map<int, int> map;
9+
10+
for ( int i = 0; i < arr_size; i++ )
11+
map[arr[i]] = i;
12+
13+
for ( int i = 0; i < arr_size - 1; i++ )
14+
for ( int j = i + 1; j < arr_size; j++ ) {
15+
int sum = value - ( arr[i] + arr[j] );
16+
17+
if ( map.find( sum ) != map.end() )
18+
if ( map[sum] != i && map[sum] != j ) {
19+
cout << '(' << arr[i] << ", " << arr[j] << ", " << sum << ')' << endl;
20+
return true;
21+
}
22+
}
23+
return false;
24+
}
25+
26+
int main()
27+
{
28+
int arr[] = { 2, 7, 4, 0, 9, 5, 1, 3 };
29+
int arr_size = sizeof( arr ) / sizeof( arr[0] );
30+
int value = 10;
31+
32+
return find_triplet( arr, arr_size, value );
33+
}

0 commit comments

Comments
 (0)