15. 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
先排序,再左右夹逼,复杂度 O(n*n)。
N-sum 的题目都可以用夹逼做,复杂度可以降一维。
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); int len = num.length, tar = 0; if (len <= 2) return ret; Arrays.sort(num); for (int i = 0; i <= len - 3; i++) { // first number : num[i] int j = i + 1; // second number int k = len - 1; // third number while (j < k) { if (num[i] + num[j] + num[k] < tar) { ++j; } else if (num[i] + num[j] + num[k] > tar) { --k; } else { ret.add(Arrays.asList(num[i], num[j], num[k])); ++j; --k; // folowing 3 while can avoid the duplications while (j < k && num[j] == num[j - 1]) ++j; while (j < k && num[k] == num[k + 1]) --k; } } while (i <= len - 3 && num[i] == num[i + 1]) ++i; } return ret; } }
题意:从一个数组中找到三个数,使这三个数的和为0。有可能存在多组解,也有可能存在重复的解,所以需要去重。比如:num=[-1,0,1,2,-1,-4];那么存在两组解:[[-1,0,1],[-1,-1,2]],解中的数需要是从小到大排序状态。
解题思路:1,先将数组排序。
2,排序后,可以按照TwoSum的思路来解题。怎么解呢?可以将num[i]的相反数即-num[i]作为target,然后从i+1到len(num)-1的数组元素中寻找两个数使它们的和为-num[i]就可以了。下标i的范围是从0到len(num)-3。
3,这个过程要注意去重。
4,时间复杂度为O(N^2)。
class Solution: # @return a list of lists of length 3, [[val1,val2,val3]] def threeSum(self, num): num.sort() res = [] for i in range(len(num)-2): if i == 0 or num[i] > num[i-1]: left = i + 1; right = len(num) - 1 while left < right: if num[left] + num[right] == -num[i]: res.append([num[i], num[left], num[right]]) left += 1; right -= 1 while left < right and num[left] == num[left-1]: left +=1 while left < right and num[right] == num[right+1]: right -= 1 elif num[left] + num[right] < -num[i]: while left < right: left += 1 if num[left] > num[left-1]: break else: while left < right: right -= 1 if num[right] < num[right+1]: break return res