[关闭]
@CrazyHenry 2018-01-01T09:42:39.000000Z 字数 1764 阅读 1093

Leetcode16. 3Sum Closest

ddddLeetcode刷题


127622-106.jpg-528kB

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

我的代码:时间复杂度O(n^2)

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-16
  4. //T(n)=O(n^2), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int threeSumClosest(vector<int>& nums, int target) {
  8. int result = 0;
  9. int min_gap = INT_MAX;
  10. //排序
  11. sort(nums.begin(),nums.end());
  12. auto vbeg = nums.begin();
  13. auto vend = nums.end();
  14. for(auto indexi = vbeg ; indexi < vend - 2; ++indexi)
  15. {
  16. auto indexj = indexi + 1;
  17. auto indexk = vend - 1;
  18. while(indexj < indexk)
  19. {
  20. auto sum = *indexi + *indexj + *indexk;
  21. auto gap = abs(sum - target);//绝对值
  22. if(gap < min_gap)
  23. {
  24. result = sum;
  25. min_gap = gap;
  26. }
  27. if(sum < target) ++indexj;
  28. else --indexk;
  29. }
  30. }
  31. return result;
  32. }
  33. };

image.png-112.3kB
分析:和上一题类似,先排序,然后夹逼;只不过,不能使用break,需要全部遍历一遍。因为以下的代码对于本题不适用:

if(3*(*indexi) > target) break;
if(2*(*indexj) > (target - *indexi)) break;//仍然可以找abs最小值

这里容易产生一个错觉,就是如果满足if(3*(*indexi) > target),那么最小结果一定是indexi与后面紧邻的两个数之和。然而实际其实并不是这样的。因为也可能是indexi与前面一个和后面一个之和。

优秀代码:时间复杂度O(n^2)

与我的代码差不多,只不过使用了一些新的STL的接口。

  1. class Solution
  2. {
  3. public:
  4. int threeSumClosest(vector<int>& nums, int target)
  5. {
  6. int result = 0;
  7. int min_gap = INT_MAX;
  8. sort(nums.begin(), nums.end());
  9. for (auto a = nums.begin(); a != prev(nums.end(), 2); ++a)
  10. {
  11. auto b = next(a);
  12. auto c = prev(nums.end());
  13. while (b < c)
  14. {
  15. const int sum = *a + *b + *c;
  16. const int gap = abs(sum - target);
  17. if (gap < min_gap)
  18. {
  19. result = sum;
  20. min_gap = gap;
  21. }
  22. if (sum < target) ++b;
  23. else --c;
  24. }
  25. }
  26. return result;
  27. }
  28. };

image.png-93.4kB

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