1 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
2 HashSet<ArrayList<Integer>> hashSet = new HashSet<ArrayList<Integer>>();
3 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
4 Arrays.sort(num);
5 for (int i = 0; i <= num.length-4; i++) {
6 for (int j = i + 1; j <= num.length-3; j++) {
7 int low = j + 1;
8 int high = num.length - 1;
9
10 while (low < high) {
11 int sum = num[i] + num[j] + num[low] + num[high];
12
13 if (sum > target) {
14 high--;
15 } else if (sum < target) {
16 low++;
17 } else if (sum == target) {
18 ArrayList<Integer> temp = new ArrayList<Integer>();
19 temp.add(num[i]);
20 temp.add(num[j]);
21 temp.add(num[low]);
22 temp.add(num[high]);
23
24 if (!hashSet.contains(temp)) {
25 hashSet.add(temp);
26 result.add(temp);
27 }
28
29 low++;
30 high--;
31 }
32 }
33 }
34 }
35
36 return result;
37 }
1 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
2 HashSet<ArrayList<Integer>> hashSet = new HashSet<ArrayList<Integer>>();
3 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
4 Arrays.sort(num);
5 for (int i = 0; i <= num.length-4; i++) {
6 if(i==0||num[i]!=num[i-1]){
7 for (int j = i + 1; j <= num.length-3; j++) {
8 if(j==i+1||num[j]!=num[j-1]){
9 int low = j + 1;
10 int high = num.length - 1;
11
12 while (low < high) {
13 int sum = num[i] + num[j] + num[low] + num[high];
14
15 if (sum > target) {
16 high--;
17 } else if (sum < target) {
18 low++;
19 } else if (sum == target) {
20 ArrayList<Integer> temp = new ArrayList<Integer>();
21 temp.add(num[i]);
22 temp.add(num[j]);
23 temp.add(num[low]);
24 temp.add(num[high]);
25
26 if (!hashSet.contains(temp)) {
27 hashSet.add(temp);
28 result.add(temp);
29 }
30
31 low++;
32 high--;
33
34 while(low<high&&num[low]==num[low-1])//remove dupicate
35 low++;
36 while(low<high&&num[high]==num[high+1])//remove dupicate
37 high--;
38 }
39 }
40 }
41 }
42 }
43 }
44
45 return result;
46 }