18. 4Sum
2017-12-22 18:17
447 查看
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length < 4) { return res; } Arrays.sort(nums); for (int i = 0; i < nums.length - 3; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int sum3 = target - nums[i]; // 后3个数之和需等于sum3 for (int j = i + 1; j < nums.length - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } int sum2 = sum3 - nums[j]; // 后2个数之和需等于sum3 int left = j + 1, right = nums.length - 1; while (left < right) { if (nums[left] + nums[right] == sum2) { List<Integer> quad = new ArrayList<>(); quad.add(nums[i]); quad.add(nums[j]); quad.add(nums[left]); quad.add(nums[right]); res.add(quad); while (left < right && nums[left++] == nums[left]) {} while (left < right && nums[right--] == nums[right]) {} } else if (nums[left] + nums[right] < sum2) { while (left < right && nums[left++] == nums[left]) {} } else { while (left < right && nums[right--] == nums[right]) {} } } } } return res; } }
相关文章推荐
- 18. 4Sum
- LeetCode#689 Maximum Sum of 3 Non-Overlapping Subarrays(week18)
- [LeetCode]18. 4Sum(自学留存)
- 类型系列题目:1. Two Sum 15,3 sum ,16 3sum closet, 18 4sum, 454 4Sum II
- 【一天一道LeetCode】#18. 4Sum
- 《LeetBook》leetcode题解(18) : 4Sum[M]
- python写算法题:leetcode: 18. 4Sum
- leetcode 18. 4Sum
- [LeetCode] 18. 4Sum
- 暑期dp46道(18)--HDOJ 1024 Max Sum Plus Plus
- 18. 4Sum(求数组中和为指定值的4个数)
- 18. 4Sum | Java最短代码实现
- 18. 4Sum
- LeetCodet题解--18. 4Sum(4个数的和)
- 【一天一道LeetCode】#18. 4Sum
- LeetCode - 18. 4Sum
- 题解——Leetcode 18. 4Sum 难度:Medium
- Project Euler 题解 #18 & #67 Maximum path sum
- Maximum path sum I [Project Euler.Problem 18]
- 18. 4Sum