[LeetCode] 18. 4Sum
Given an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
,b
,c
, andd
are distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]]
Constraints:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
四数之和。
给你一个由 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
你可以按 任意顺序 返回答案 。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/4sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
依然是双指针逼近的思路做,注意以下几点
- 需要对 input 排序
- 需要四个指针 - i, j, low, high
- 每个指针都需要跳过重复元素
- i 最多到 nums.length - 3
时间O(n^3)
空间O(n) - output
Java实现 - 可以处理整型溢出的问题(19行)
1 class Solution { 2 public List<List<Integer>> fourSum(int[] nums, int target) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if (nums.length < 4) { 5 return res; 6 } 7 Arrays.sort(nums); 8 for (int i = 0; i < nums.length - 3; i++) { 9 if (i > 0 && nums[i] == nums[i - 1]) { 10 continue; 11 } 12 for (int j = i + 1; j < nums.length - 2; j++) { 13 if (j > i + 1 && nums[j] == nums[j - 1]) { 14 continue; 15 } 16 int low = j + 1; 17 int hi = nums.length - 1; 18 while (low < hi) { 19 long sum = (long) target - nums[i] - nums[j]; 20 if (nums[low] + nums[hi] == sum) { 21 res.add(Arrays.asList(nums[i], nums[j], nums[low], nums[hi])); 22 while (low < hi && nums[low] == nums[low + 1]) { 23 low++; 24 } 25 while (low < hi && nums[hi] == nums[hi - 1]) { 26 hi--; 27 } 28 low++; 29 hi--; 30 } else if (nums[low] + nums[hi] < sum) { 31 low++; 32 } else { 33 hi--; 34 } 35 } 36 } 37 } 38 return res; 39 } 40 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number[][]} 5 */ 6 var fourSum = function(nums, target) { 7 nums = nums.sort((a, b) => a - b); 8 const res = []; 9 let low, high, sum; 10 // corner case 11 if (nums.length < 4) return res; 12 13 // normal case 14 for (let i = 0; i < nums.length - 3; i++) { 15 if (i > 0 && nums[i] === nums[i - 1]) continue; 16 for (let j = i + 1; j < nums.length - 2; j++) { 17 if (j > i + 1 && nums[j] === nums[j - 1]) continue; 18 low = j + 1; 19 high = nums.length - 1; 20 while (low < high) { 21 sum = nums[i] + nums[j] + nums[low] + nums[high]; 22 if (sum === target) { 23 res.push([nums[i], nums[j], nums[low], nums[high]]); 24 while (low < high && nums[low] === nums[low + 1]) low++; 25 while (low < high && nums[high] === nums[high - 1]) high--; 26 low++; 27 high--; 28 } else if (sum < target) { 29 low++; 30 } else { 31 high--; 32 } 33 } 34 } 35 } 36 return res; 37 };