/*
题目:四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,
判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?
找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
思路:
和三叔和基本一样,多了层循环。可参考15-threeSum
*/
package leetCode.DoublePointer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class lc_dbp_18_fourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length == 0)
return ans;
Arrays.sort(nums);//排序
for (int a = 0; a < nums.length; a++) {
if (a > 0 && nums[a] == nums[a - 1])//移动后数字要变化,不然ans有重复
continue;
for (int b = a + 1; b < nums.length; b++) {
// 注意:这里哦j>i+1,不是j>0,因为这里是以i+1为起点为第一个,所以重复的条件是j>i+1
// 如果直接写j>0,那么当num[0]=num[1]时,j=1将被跳过,答案错误
if (b > a + 1 && nums[b] == nums[b - 1])//移动后数字要变化,不然ans有重复
continue;
int L = b + 1;
int R = nums.length - 1;
while (L < R) {
int sum = nums[a] + nums[b] + nums[L] + nums[R];
if (sum < target)
L++;
else if (sum > target)
R--;
else {
ArrayList<Integer> list = new ArrayList<>();
list.add(nums[a]);
list.add(nums[b]);
list.add(nums[L]);
list.add(nums[R]);
ans.add(list);
while (L < R && nums[L + 1] == nums[L])
L++;
while (L < R && nums[R - 1] == nums[R])
R--;
L++;
R--;
}
}
}
}
return ans;
}
}