-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path28) Triplet Sum in Array.cpp
49 lines (43 loc) · 1.1 KB
/
28) Triplet Sum in Array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
using namespace std;
/*
//Time Limit Exceeded
bool find3Numbers(int A[], int n, int X){
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
for(int k=j+1; k<n; k++){
int sum = A[i] + A[j] + A[k];
if(sum==X){
return true;
}else{
continue;
}
}
}
}
return false;
}*/
//By using unordered_set
bool find3Numbers(int A[], int n, int X){
//unordered_set
for(int i=0; i<n-2; i++){
unordered_set<int> uset;
int localSum = X - A[i]; // take the first element and subtract
for(int j=i+1; j<n; j++){
if(uset.find(localSum - A[j]) != uset.end()){
return true;
}
uset.insert(A[j]);
}
}
return false;
}
//Main method
int main(){
int arr[] = {1, 4, 45, 6, 10, 8};
int n = sizeof(arr)/sizeof(arr[0]);
int K = 13;
//call method
find3Numbers(arr, n, K);
return 0;
}