1. 题目描述
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:答案中不可以包含重复的四元组。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [], target = 0
输出:[]
提示:
0 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 题解
思路:参考 15. 三数之和的思路的思路,这里不过是多了一重循环。
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
//声明返回结果
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
if(n < 4){
return res;
}
//首先对数组排序
Arrays.sort(nums);
//循环1
for(int a = 0; a < n; a++){
//去重
if(a != 0 && nums[a] == nums[a-1]){
continue;
}
//循环2
for(int b = a+1; b < n; b++){
//去重
if(b != a+1 && nums[b] == nums[b-1]){
continue;
}
//循环3
for(int c = b+1; c < n; c++){
//去重
if(c != b+1 && nums[c] == nums[c-1]){
continue;
}
int d = n-1;
while(c < d && nums[a] + nums[b] + nums[c] > target - nums[d]){
d--;
}
//此轮没有结果
if(c == d){
break;
}
//此轮有结果并记录
if(nums[a] + nums[b] + nums[c] == target - nums[d]){
List<Integer> list = new ArrayList<>();
list.add(nums[a]);
list.add(nums[b]);
list.add(nums[c]);
list.add(nums[d]);
res.add(list);
}
}
}
}
return res;
}
}
时间复杂度:O(nnn),因为是三重循环,最开始的数组排序只需要O(n*logn);
空间复杂度:这里取决于排序使用的额外的空间,像快排在递归时使用的栈空间大小是O(logn)。