3Sum Closest

描述

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(n2)O(n^2)

代码

  1. // 3Sum Closest
  2. // 先排序,然后左右夹逼//
  3. // Time Complexity: O(n^2), Space Complexity: O(1)
  4. class Solution {
  5. public:
  6. int threeSumClosest(vector<int>& nums, int target) {
  7. int result = 0;
  8. int min_gap = INT_MAX;
  9. sort(nums.begin(), nums.end());
  10. for (auto a = nums.begin(); a != prev(nums.end(), 2); ++a) {
  11. auto b = next(a);
  12. auto c = prev(nums.end());
  13. while (b < c) {
  14. const int sum = *a + *b + *c;
  15. const int gap = abs(sum - target);
  16. if (gap < min_gap) {
  17. result = sum;
  18. min_gap = gap;
  19. }
  20. if (sum < target) ++b;
  21. else --c;
  22. }
  23. }
  24. return result;
  25. }
  26. };

相关题目

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