18. 4Sum

题目:

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.

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]
]

链接:https://leetcode.com/problems/4sum/#/description

4/11/2017

88ms, 28%

写错了无数遍。

注意的问题:

1. 外层的遍历并不是从头尾一起开始的,而是都是从一个方向开始的。注意第7行的终止条件

2. while循环当中的判断,并且注意28, 29行

 1 public class Solution {
 2     public List<List<Integer>> fourSum(int[] nums, int target) {
 3         if (nums == null || nums.length < 4) return new ArrayList<>();
 4         List<List<Integer>> ret = new ArrayList<>();
 5 
 6         Arrays.sort(nums);
 7         for (int i = 0; i < nums.length - 3; i++) {
 8             if (i > 0 && nums[i] == nums[i - 1]) {
 9                 continue;
10             }
11             for (int j = i + 1; j < nums.length - 2; j++) {
12                 if (j > i + 1 && nums[j] == nums[j - 1]) {
13                     continue;
14                 }
15                 int left = j + 1, right = nums.length - 1;
16 
17                 while (left < right) {
18                     int sum = nums[left] + nums[right] + nums[i] + nums[j];
19                     if (sum == target) {
20                         List<Integer> l = new ArrayList<Integer>();
21                         l.add(nums[i]);
22                         l.add(nums[left]);
23                         l.add(nums[right]);
24                         l.add(nums[j]);
25                         ret.add(l);
26                         left++;
27                         right--;
28                         while (left < right && nums[left] == nums[left - 1]) left++;
29                         while (left < right && nums[right] == nums[right + 1]) right--;
30                     } else if (sum < target) {
31                         left++;
32                     } else {
33                         right--;
34                     }
35                 }
36             }
37         }
38         return ret;
39     }
40 }

别人的做法:

把kSum变为2sum来解。

https://discuss.leetcode.com/topic/29585/7ms-java-code-win-over-100/17

还有解释时间复杂度lower case

https://discuss.leetcode.com/topic/27445/lower-bound-n-3

更多讨论:

https://discuss.leetcode.com/category/26/4sum

原文地址:https://www.cnblogs.com/panini/p/6697211.html