题目来源
题目描述
给定一个含有 n 个整数的数组 S,数列 S 中是否存在元素 a,b,c 和 d 使 a + b + c + d = target ?
请在数组中找出所有满足各元素相加等于特定值 的 不重复 组合。
注意:解决方案集不能包含重复的四元组合。
例如,给定数组 S = [1, 0, -1, 0, -2, 2],并且给定 target = 0。
示例答案为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
解决方案
Java
同三数之和,固定前两个数,对剩下的两个数使用两边夹方法,该算法时间复杂度为 O(n3) O ( n 3 ) 。
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> arr=new ArrayList<>();
Arrays.sort(nums);//排序
for(int i=0;i<nums.length-3;i++){
if(i>0 && nums[i]==nums[i-1]){//防止第一个数重复
continue;
}
for(int j=i+1;j<nums.length-2;j++){
if(j>i+1 && nums[j]==nums[j-1]){//防止第二个数重复
continue;
}
int k=j+1;
int m=nums.length-1;
while (k<m){
if(k>j+1 && nums[k]==nums[k-1]){//防止第三个数重复
k++;
continue;
}
if(m<nums.length-1 && nums[m]==nums[m+1]){//防止第四个数重复
m--;
continue;
}
int res=nums[i]+nums[j]+nums[k]+nums[m];
if(res<target){
k++;
}else if(res>target){
m--;
}else{
arr.add(Arrays.asList(nums[i],nums[j],nums[k],nums[m]));
k++;
m--;
}
}
}
}
return arr;
}
}