LeetCode-18. 四数之和
题目来源
题目详情
给你一个由 n
个整数组成的数组 nums
,和一个目标值 target
。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]]
(若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a
、b
、c
和d
互不相同nums[a] + nums[b] + nums[c] + nums[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 = [2,2,2,2,2], target = 8
输出: [[2,2,2,2]]
提示:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
相似题目
题解分析
解法一:双指针法-nSum问题模板
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int n = nums.length;
Arrays.sort(nums);
return nSum(nums, 4, 0, target);
}
private List<List<Integer>> nSum(int[] sum ,int n, int pos, int target){
int size = sum.length;
List<List<Integer>> res = new ArrayList<>();
if(n < 2 || size < n){
return res;
}else if(n == 2){
int left = pos, right = size-1;
while(left < right){
int tempsum = sum[left] + sum[right];
int leftnum = sum[left], rightnum = sum[right];
if(tempsum < target){
while(left < right && sum[left] == leftnum){
left++;
}
}else if(tempsum > target){
while(left < right && sum[right] == rightnum){
right--;
}
}else{
List<Integer> list = new ArrayList<>(){{
add(leftnum);
add(rightnum);
}};
res.add(list);
while(left < right && sum[left] == leftnum){
left++;
}
while(left < right && sum[right] == rightnum){
right--;
}
}
}
}else{
for(int i=pos; i<size; i++){
int num = sum[i];
List<List<Integer>> ans = nSum(sum, n-1, i+1, target-num);
for(List<Integer> temp : ans){
temp.add(num);
res.add(temp);
}
while(i < size - 1 && sum[i] == sum[i+1]){
i++;
}
}
}
return res;
}
}
参考
Either Excellent or Rusty