给你一个由 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:
1 2
| 输入:nums = [1,0,-1,0,-2,2], target = 0 输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
|
示例 2:
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
三数之和的双指针解法是一层for循环num[i]为确定值,然后循环内有left和right下标作为双指针,找到nums[i] + nums[left] + nums[right] == 0。
四数之和的双指针解法是两层for循环nums[k] + nums[i]为确定值,依然是循环内有left和right下标作为双指针,找出nums[k] + nums[i] + nums[left] + nums[right] == target的情况
三数之和的时间复杂度是$O(n^2)$,
四数之和的时间复杂度是$O(n^3)$ 。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> ans = new ArrayList<>(); List<Integer> path = new ArrayList<>(); Arrays.sort(nums);
for(int i = 0; i < nums.length ; i++){ if(i > 0 && nums[i] == nums[i -1 ]){ continue; } for(int j = i + 1; j < nums.length; j++){ if(j > i + 1 && nums[j] == nums[j-1]){ continue; } int left = j + 1; int right = nums.length-1; while(left < right){ long sum = (long)nums[i] + nums[j] + nums[left] + nums[right]; if(sum > target){ right--; }else if(sum < target){ left ++; }else{ Collections.addAll(path, nums[i], nums[j], nums[left], nums[right]); ans.add(new ArrayList<>(path)); path.clear(); while(left < right && nums[left] == nums[left + 1]) left ++; while(left < right && nums[right] == nums[right - 1]) right --; left ++; right --; } } } } return ans; } }
|
- 时间复杂度: $O(n^3)$
- 空间复杂度: $O(1)$