-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTriplet sum in array in cpp
67 lines (59 loc) · 1.03 KB
/
Triplet sum in array in 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//Using hash map
```
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n=6;
int a[n]={1,4,6,7,8,9};
int x=24;
for(int i=0;i<n-1;i++)
{
unordered_set<int>s;
int cs=x-a[i];
cout<<"cs"<<cs<<endl;
for(int j=i+1;j<n;j++)
{
if(s.find(cs-a[j])!=s.end())
{
cout<<a[i]<<" "<<a[j]<<" "<<cs-a[j]<<endl;
}
s.insert(a[j]);
}
}
return 0;
}
```
// by using normal method
```
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n=6;
int a[n]={1,2,3,4,10,45};
int x=57;
for(int i=0;i<n;i++)
{
int l=i+1;
int r=n-1;
while(l<r)
{
int sum=a[i]+a[l]+a[r];
if(sum==x)
{
cout<<a[i]<<" "<<a[l]<<" "<<a[r];
break;
}
else if(sum>x)
{
r--;
}
else
{
l++;
}
}
}
return 0;
}