题目
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:答案中不可以包含重复的四元组。
**代码
**
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
int len = nums.length;
//特判
if(nums == null || len < 4) return list;
//排序
Arrays.sort(nums);
//循环
for(int i = 0 ;i < len - 3 ;i++){//固定i
if(i > 0 && nums[i] == nums[i - 1])continue;//去重
for(int j = i + 1; j < len - 2;j++){//固定j
if( j > i + 1 && nums[j] == nums[j - 1])continue; //去重
int L = j + 1;
int R = len - 1;
while( L < R) {
int sum = nums[i] + nums[L] + nums[R] + nums[j];
if(sum == target){
list.add(Arrays.asList(nums[i],nums[j],nums[L],nums[R]));
while(L < R && nums[L] == nums[L + 1]) L++;//去重
while(L < R && nums[R] == nums[R - 1]) R--;//去重
L ++;
R --;
}
else if(sum < target) L++;
else if(sum > target) R--;
}
}
}
return list;
}
}