-
Notifications
You must be signed in to change notification settings - Fork 0
/
4sum_number
35 lines (35 loc) · 1.12 KB
/
4sum_number
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
vector<vector<int> > fourSum(vector<int> &arr, int k) {
int n = arr.size();
vector<vector<int>>res;
sort(arr.begin(), arr.end());
for (int i = 0; i < n - 3; i++)
{
if (i > 0 && arr[i - 1] == arr[i])
continue;
for (int j = i + 1; j < n - 2; j++)
{
if (j > i + 1 && arr[j] == arr[j - 1])
continue;
int l = j + 1, h = n - 1;
while (l < h)
{
int sum = arr[i] + arr[j] + arr[l] + arr[h];
if (sum == k)
{
res.push_back({arr[i], arr[j], arr[l], arr[h]});
l++;
h--;
while (l < h && arr[l] == arr[l - 1])
l++;
while (h > l && arr[h] == arr[h + 1])
h--;
}
else if (sum < k)
l++;
else
h--;
}
}
}
return res;
}