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. class Solution {
  5. public:
  6. vector<vector<int>> threeSum(vector<int>& nums) {
  7. vector<vector<int>> result;
  8. if (nums.size() < 3) return result;
  9. sort(nums.begin(), nums.end());
  10. const int target = 0;
  11. auto last = nums.end();
  12. for (auto i = nums.begin(); i < last-2; ++i) {
  13. if (i > nums.begin() && *i == *(i-1)) continue;
  14. auto j = i+1;
  15. auto k = last-1;
  16. while (j < k) {
  17. if (*i + *j + *k < target) {
  18. ++j;
  19. while(*j == *(j - 1) && j < k) ++j;
  20. } else if (*i + *j + *k > target) {
  21. --k;
  22. while(*k == *(k + 1) && j < k) --k;
  23. } else {
  24. result.push_back({ *i, *j, *k });
  25. ++j;
  26. --k;
  27. while(*j == *(j - 1) && j < k) ++j;
  28. while(*k == *(k + 1) && j < k) --k;
  29. }
  30. }
  31. }
  32. return result;
  33. }
  34. };

相关题目

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