[关闭]
@CrazyHenry 2018-01-01T09:43:55.000000Z 字数 1616 阅读 1316

Leetcode15. 3Sum

ddddLeetcode刷题


wallhaven-569825.jpg-444.8kB

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

image.png-75.7kB

我的代码:

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-15
  4. //T(n)=O(n^2), S(n)=O(1)
  5. class Solution {
  6. public:
  7. vector<vector<int>> threeSum(vector<int>& nums)
  8. {
  9. if(nums.size() < 3) return vector<vector<int>>();
  10. vector<vector<int>> result;
  11. //排序
  12. sort(nums.begin(),nums.end());
  13. auto vbeg = nums.begin();
  14. auto vend = nums.end();
  15. constexpr int target = 0;
  16. for(auto indexi = vbeg ; indexi < vend - 2; ++indexi)
  17. {
  18. if(3*(*indexi) > target) break;//见分析
  19. if(*indexi == *(indexi - 1) && indexi > vbeg) continue;//见分析
  20. auto indexj = indexi + 1;
  21. auto indexk = vend - 1;
  22. while(indexj < indexk)
  23. {
  24. if(*indexi + *indexj + *indexk > target)
  25. {
  26. --indexk;
  27. while(*indexk == *(indexk + 1) && indexj < indexk) --indexk;
  28. }
  29. else if(*indexi + *indexj + *indexk < target)
  30. {
  31. ++indexj;
  32. while(*indexj == *(indexj - 1) && indexj < indexk) ++indexj;
  33. if(2*(*indexj) > (target - *indexi)) break;
  34. }
  35. else //*i + *j + *k = target
  36. {
  37. result.push_back({*indexi,*indexj,*indexk});
  38. --indexk;
  39. ++indexj;
  40. while(*indexj == *(indexj - 1) && indexj < indexk) ++indexj;
  41. while(*indexk == *(indexk + 1) && indexj < indexk) --indexk;
  42. }
  43. }
  44. }
  45. return result;
  46. }
  47. };

image.png-113.5kB
分析:
image.png-54.5kB

  1. if(3*(*indexi) > target) break;
  2. if(2*(*indexj) > (target - *indexi)) break;
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注