[关闭]
@CrazyHenry 2018-01-01T09:41:55.000000Z 字数 1321 阅读 1170

leetcode18. 4Sum

ddddLeetcode刷题


38933-106.jpg-527.7kB

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

分析:

还是采用左右夹逼的方式,只不过又多了一层循环。不能重复控制起来比较麻烦,不如直接查找是否重复来简化。

我的代码:

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-18
  4. //T(n)=O(n^3), S(n)=O(1)
  5. //先排序,然后左右夹逼,最后剔除重复case
  6. class Solution {
  7. public:
  8. vector<vector<int>> fourSum(vector<int>& nums, int target) {
  9. vector<vector<int>> result;
  10. if(nums.size() < 4) return result;
  11. sort(nums.begin(),nums.end());
  12. for(auto a = nums.begin(); a != prev(nums.end(), 3); ++a)
  13. for(auto b = next(a); b != prev(nums.end(), 2); ++b)
  14. {
  15. auto c = next(b);
  16. auto d = prev(nums.end());
  17. while(c < d)
  18. {
  19. if(*a + *b + *c + *d < target)
  20. ++c;
  21. else if(*a + *b + *c + *d > target)
  22. --d;
  23. else
  24. {
  25. result.push_back({*a,*b,*c,*d});
  26. ++c;
  27. --d;
  28. }
  29. }
  30. }
  31. sort(result.begin(), result.end());
  32. result.erase(unique(result.begin(),result.end()), result.end());
  33. return result;
  34. }
  35. };

image.png-121.6kB

更多利用STL的解法以后再讨论。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注