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≤ca \leq b \leq ca≤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. (-1, 0, 1)
  2. (-1, -1, 2)

分析

先排序,然后左右夹逼,复杂度 O(n2)O(n^2)

这个方法可以推广到k-sum,先排序,然后做k-2次循环,在最内层循环左右夹逼,时间复杂度是 O(max{nlogn,nk1})O(\max{n \log n, n^{k-1}})

代码

  1. // 3Sum
  2. // 先排序,然后左右夹逼,注意跳过重复的数
  3. // Time Complexity: O(n^2),Space Complexity: O(1)
  4. public class Solution {
  5. public List<List<Integer>> threeSum(int[] nums) {
  6. List<List<Integer>> result = new ArrayList<>();
  7. if (nums.length < 3) return result;
  8. Arrays.sort(nums);
  9. final int target = 0;
  10. for (int i = 0; i < nums.length - 2; ++i) {
  11. if (i > 0 && nums[i] == nums[i-1]) continue;
  12. int j = i+1;
  13. int k = nums.length-1;
  14. while (j < k) {
  15. if (nums[i] + nums[j] + nums[k] < target) {
  16. ++j;
  17. while(nums[j] == nums[j-1] && j < k) ++j;
  18. } else if(nums[i] + nums[j] + nums[k] > target) {
  19. --k;
  20. while(nums[k] == nums[k+1] && j < k) --k;
  21. } else {
  22. result.add(Arrays.asList(nums[i], nums[j], nums[k]));
  23. ++j;
  24. --k;
  25. while(nums[j] == nums[j-1] && j < k) ++j;
  26. while(nums[k] == nums[k+1] && j < k) --k;
  27. }
  28. }
  29. }
  30. return result;
  31. }
  32. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/array/3sum.html