1 import java.util.ArrayList;
2 import java.util.Arrays;
3 import java.util.List;
4
5 public class Solution {
6 public static List<List<Integer>> fourSum(int[] nums, int target) {
7 List<List<Integer>> res = new ArrayList<>();
8 Arrays.sort(nums);
9 int length = nums.length;
10 if(length==4 && nums[0]+nums[1] + nums[2] + nums[3]==target) {
11 res.add(Arrays.asList(nums[0], nums[1], nums[2], nums[3]));
12 return res;
13 }
14 for(int i=0; i<length-3; i++){
15 // 当前的最小情况:若前四个加起来都大于了,就跳出遍历;
16 // 当前的最大情况:若此处的+后三个都小于了,那么就继续下一个判断。
17 if (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) {
18 break;
19 }
20 if (nums[i] + nums[length-1] + nums[length-2] + nums[length-3] < target) {
21 continue;
22 }
23
24 // 最外层的去重方法
25 if(i>0 && nums[i]==nums[i-1]) {
26 continue;
27 }
28
29 for(int j=i+1; j<length-2; j++) {
30 if (nums[j] == nums[j-1] && j>i+1) { continue; }
31 int leftP = j+1;
32 int rightP = length-1;
33 while(leftP<rightP) {
34 int temp = nums[i] + nums[j] + nums[leftP] + nums[rightP];
35 if (temp < target) {
36 leftP += 1;
37 } else if (temp > target) {
38 rightP -= 1;
39 } else {
40 res.add(Arrays.asList(nums[i], nums[j], nums[leftP], nums[rightP]));
41 // 内层的左指针去重方法,注意是一直到不重复,所以用while
42 while (leftP < rightP && nums[leftP]==nums[leftP+1]) {
43 leftP += 1;
44 }
45 // 内层的右指针去重
46 while (leftP < rightP && nums[rightP]==nums[rightP-1]) {
47 rightP -= 1;
48 }
49 leftP += 1;
50 rightP -= 1;
51 }
52 }
53 }
54
55 }
56 return res;
57 }
58 }