【Leetcode】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).
 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int>& num, int target) {
 4         int result = 0;
 5         int min_gap = INT_MAX;
 6         sort(num.begin(), num.end());
 7         for (size_t i = 0; i < num.size() - 2; ++i) {
 8             if (i > 0 && num[i] == num[i - 1]) continue;
 9             size_t j = i + 1, k = num.size() - 1;
10             while (j < k) {
11                 int sum = num[i] + num[j] + num[k];
12                 int gap = abs(sum - target);
13                 if (gap < min_gap) {
14                     min_gap = gap;
15                     result = sum;
16                 }
17                 if (sum < target) {
18                     ++j;
19                 } else if (sum > target) {
20                     --k;
21                 } else {
22                     return result;
23                 }
24             }
25         }
26         return result;
27     }
28 };
View Code

与上题3Sum类似,先排序,然后以一个元素为准,两边夹逼,逐个求三个元素的和,找到与目标相等的了可以直接返回,对于重复元素可以只找一次。

原文地址:https://www.cnblogs.com/dengeven/p/3606227.html