-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4Sum
More file actions
35 lines (35 loc) · 1.15 KB
/
4Sum
File metadata and controls
35 lines (35 loc) · 1.15 KB
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
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
if (i > 0 && num[i] == num[i - 1])
continue;
for (int j = i + 1; j < num.length; j++) {
if (j > i + 1 && num[j] == num[j - 1] )
continue;
int p = j + 1, q = num.length - 1;
while (p < q) {
int sum = num[i] + num[j] + num[p] + num[q];
if (sum == target) {
ArrayList quad = new ArrayList();
quad.add(num[i]);
quad.add(num[j]);
quad.add(num[p]);
quad.add(num[q]);
result.add(quad);
do {p++;} while (p < q && num[p] == num[p - 1]);
do {q--;} while (p < q && num[q] == num[q + 1]);
} else if (sum < target) {
p++;
} else {
q--;
}
}
}
}
return result;
}
}