18. 四数之和 4Sum
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c+ d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Notice that the solution set must not contain duplicate quadruplets.
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
方法类似于三数相加
也是双指针,有些情况可以优化,比如最前四个相加大于target可以退出,最后四个相加小于target可以退出。再就是去掉重复的。
public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> ans = new ArrayList<>(); int n = nums.length; if (n < 4) { return ans; } Arrays.sort(nums); for (int first = 0; first < n - 3; first++) { if (nums[first] + nums[first + 1] + nums[first + 2] + nums[first + 3] > target) break; if (nums[first] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) continue; if (first > 0 && nums[first] == nums[first - 1]) { continue; } for (int second = first + 1; second < n - 2; second++) { if (nums[first] + nums[second] + nums[second + 1] + nums[second + 2] > target) break; if (nums[first] + nums[second] + nums[n - 2] + nums[n - 1] < target) continue; if (second > first + 1 && nums[second] == nums[second - 1]) { continue; } int forth = n - 1; for (int third = second + 1; third < forth; ) { int sum = nums[first] + nums[second] + nums[third] + nums[forth]; if (sum == target) { List<Integer> ans_one = new ArrayList<>(); ans_one.add(nums[first]); ans_one.add(nums[second]); ans_one.add(nums[third]); ans_one.add(nums[forth]); ans.add(ans_one); while (third < forth && nums[third] == nums[third + 1]) { third++; } third++; while (third < forth && nums[forth] == nums[forth - 1]) { forth--; } forth--; } else if (sum < target) { third++; } else { forth--; } } } } return ans; }
参考链接:
https://leetcode.com/problems/4sum/
https://leetcode-cn.com/problems/4sum/