forked from imnurav/Hactoberfest2021-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSum.cpp
57 lines (47 loc) · 1.7 KB
/
TwoSum.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
/*
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
*/
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> threeSum(vector<int>& num) {
vector<vector<int>> res;
sort(num.begin(), num.end());
// moves for a
for (int i = 0; i < (int)(num.size())-2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int lo = i+1, hi = (int)(num.size())-1, sum = 0 - num[i];
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
vector<int> temp;
temp.push_back(num[i]);
temp.push_back(num[lo]);
temp.push_back(num[hi]);
res.push_back(temp);
while (lo < hi && num[lo] == num[lo+1]) lo++;
while (lo < hi && num[hi] == num[hi-1]) hi--;
lo++; hi--;
}
else if (num[lo] + num[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}
int main(){
int n;
cout<<"Enter Size of array: ";
cin>>n;
int k;
cout<<"Enter the target sum: ";
cin>>k;
cout<<"Enter the array elements: ";
vector<int>arr(n);
for(int i=0;i<n;i++)
cin>>arr[i];
vector<int>res=threeSum(arr);
for(int i=0;i<res.size();i++)
cout<<res[i][0]<<" "<res[i][1]<<" "<<res[i][2]<<endl;
}