forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4sumC++
59 lines (40 loc) · 1.86 KB
/
4sumC++
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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int> > res;
if (num.empty())
return res;
int n = num.size();
sort(num.begin(),num.end());
for (int i = 0; i < n; i++) {
int target_3 = target - num[i];
for (int j = i + 1; j < n; j++) {
int target_2 = target_3 - num[j];
int front = j + 1;
int back = n - 1;
while(front < back) {
int two_sum = num[front] + num[back];
if (two_sum < target_2) front++;
else if (two_sum > target_2) back--;
else {
vector<int> quadruplet(4, 0);
quadruplet[0] = num[i];
quadruplet[1] = num[j];
quadruplet[2] = num[front];
quadruplet[3] = num[back];
res.push_back(quadruplet);
// Processing the duplicates of number 3
while (front < back && num[front] == quadruplet[2]) ++front;
// Processing the duplicates of number 4
while (front < back && num[back] == quadruplet[3]) --back;
}
}
// Processing the duplicates of number 2
while(j + 1 < n && num[j + 1] == num[j]) ++j;
}
// Processing the duplicates of number 1
while (i + 1 < n && num[i + 1] == num[i]) ++i;
}
return res;
}
};