-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfourSum.cpp
131 lines (127 loc) · 3.92 KB
/
fourSum.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <bits/stdc++.h>
using namespace std;
// class Solution{
// public:
// vector<vector<int>> fourSum(vector<int> arr, int k)
// {
// int n = arr.size();
// set<vector<int>> st;
// for(int i = 0; i< n; i++)
// {
// for(int j = i+1; j< n; j++)
// {
// for(int k = j+1; k < n; k++)
// {
// for(int l = k+1; l < n; l++)
// {
// if(arr[i]+arr[j]+arr[k]+arr[l] == k)
// {
// vector<int> temp = {arr[i], arr[j], arr[k],arr[l]};
// sort(temp.begin(), temp.end());
// st.insert(temp);
// }
// }
// }
// }
// }
// vector<vector<int>> res(st.begin(), st.end());
// }
// };
// broute force solution whose time complexity is o(n^4).
// class Solution
// {
// public:
// vector<vector<int>> fourSum(vector<int> arr, int target)
// {
// int n = arr.size();
// set<vector<int>> st;
// for (int i = 0; i <n; i++)
// {
// for (int j = i + 1; j <n; j++)
// {
// set<int> hash;
// for (int k = j + 1; k <n; k++)
// {
// int sum = arr[i] + arr[j]+ arr[k];
// int fourth = target - sum;
// if (hash.find(fourth) != hash.end())
// {
// vector<int> temp = {arr[i], arr[j], arr[k], fourth};
// sort(temp.begin(), temp.end());
// st.insert(temp);
// }
// hash.insert(arr[k]);
// }
// }
// }
// vector<vector<int>> res(st.begin(), st.end());
// return res;
// }
// };
// this is the better solution whose time complexity is o(n^3)+o(nlogn) and space o(n)+o(to store 4 elements).
class Solution
{
public:
vector<vector<int>> fourSum(vector<int> arr, int target)
{
int n = arr.size();
sort(arr.begin(), arr.end());
vector<vector<int>> ans;
for(int i = 0; i< n; i++)
{
for(int j = i+1; j< n; j++)
{
if(j!=i+1 && arr[j] == arr[j-1])
{
continue;
}
int k = j+1;
int l = n-1;
while(k < l)
{
int sum = arr[i]+arr[j];
sum += (arr[k]+arr[l]);
if(sum < 0)
{
k++;
}
else if(sum > 0)
{
l--;
}
else{
vector<int> temp = {arr[i], arr[j], arr[k], arr[l]};
ans.push_back(temp);
k++;
l--;
while(arr[k] == arr[k-1] && k < l)
k++;
while(arr[l]==arr[l+1] && k < l)
l--;
}
}
}
}
return ans;
}
};
// this is optimal solution whose time complexity is o(n^n)+o(nlogn) and space complexity is O(4th elment store).
int main()
{
vector<int> v = {1, 0, -1, 0, -2, 2};
cout<< "the code is running"<<endl;
Solution s;
int k = 0;
vector<vector<int>> a = s.fourSum(v, k);
int n = a.size();
int m = a[0].size();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}