forked from spandey1296/Learn-Share-Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3Sum_Problem.cpp
64 lines (58 loc) ยท 1.48 KB
/
3Sum_Problem.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
// A program to find all Unique triplets whose sum equals to 0
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> threeSum(vector<int> &num)
{
vector<vector<int>> res;
sort(num.begin(), num.end());
for (int i = 0; i < num.size(); i++)
{
int target = -num[i];
int front = i + 1;
int back = num.size() - 1;
while (front < back)
{
int sum = num[front] + num[back];
if (sum < target)
front++;
else if (sum > target)
back--;
else
{
vector<int> triplet = {num[i], num[front], num[back]};
res.push_back(triplet);
while (front < back && num[front] == triplet[1])
front++;
while (front < back && num[back] == triplet[2])
back--;
}
}
while (i + 1 < num.size() && num[i + 1] == num[i])
i++;
}
return res;
}
int main()
{
int n, i, element;
cout << "Enter the size of array : ";
cin >> n;
vector<int> arr;
vector<vector<int>> ans;
cout<<"Enter array elements "<<endl;
for (i = 0; i < n; i++)
{
cin >> element;
arr.push_back(element);
}
ans = threeSum(arr);
cout << "Unique Triplets with sum equal to 0 are"<<endl;
for (auto x : ans)
{
for (auto i : x)
{
cout << i << " ";
}
cout << endl;
}
}