forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4sumJava
60 lines (39 loc) · 1.88 KB
/
4sumJava
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
class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
if (num == null || num.length == 0)
return res;
int n = num.length;
Arrays.sort(num);
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 {
List<Integer> quad = new ArrayList();
quad.add(num[i]);
quad.add(num[j]);
quad.add(num[front]);
quad.add(num[back]);
res.add(quad);
// Processing the duplicates of number 3
while (front < back && num[front] == quad.get(2)) ++front;
// Processing the duplicates of number 4
while (front < back && num[back] == quad.get(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;
}
}