解题思路:
1、同三数之和思路,双指针遍历(双层for循环+双指针)
1、先对传入的数组进行判断
2、对数组进行排序,a+b+c+d = sum,a和b采用for循环,且要注意a b不能取相同的值,如果有直接跳过
3、对sum与target进行比较,如果sum>target,则需要d左移;否则c右移
4、当sum=target时,也要对c和d进行判重,跳过重复的情况;c右移、d左移
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
if (nums.length < 4 || nums == null){
return list;
}
Arrays.sort(nums);
int length = nums.length;
for (int first = 0; first < length; first++) {
if (first > 0 && nums[first] == nums[first - 1]) continue;
for (int second = first+1; second < length; second++) {
if (second > first + 1 && nums[second] == nums[second - 1]) continue;
int third = second + 1;
int fourth = length - 1;
while (third < fourth){
int sum = nums[first] + nums[second] + nums[third] + nums[fourth];
if (sum > target) fourth--;
else if (sum < target) third++;
else {
List<Integer> subList = new ArrayList<>();
subList.add(nums[first]);
subList.add(nums[second]);
subList.add(nums[third]);
subList.add(nums[fourth]);
list.add(subList);
while (third < fourth && nums[third] == nums[third + 1]) third++;
while (third < fourth && nums[fourth] == nums[fourth -1]) fourth--;
third++;
fourth--;
}
}
}
}
return list;
}
1、first从0开始,second不能从1开始,而是要从first+1开始;(如果second从1开始,那么在first跳重之后,first、second将指向了同一个数字)