[LeetCode] #16 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).

 本文是3sum问题的变更,是寻找到最接近目标值的三数组合,利用diff存放与目标最小的差距,如果diff=0,即可输出。

参考的3sum问题http://www.cnblogs.com/Scorpio989/p/4440236.html

时间:15ms。代码如下:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int besttarget = 0, diff = INT_MAX;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 2; i++){
            int j = i + 1, n = nums.size() - 1;
            if (i>0 && nums[i] == nums[i - 1])
                continue;
            while (j < n){
                if (j>i + 1 && nums[j] == nums[j - 1]){
                    j++;
                    continue;
                }
                if (n<nums.size() - 1 && nums[n] == nums[n + 1]){
                    n--;
                    continue;
                }
                int sum = nums[i] + nums[j] + nums[n];
                if (abs(sum - target) < diff){
                    diff = abs(sum - target);
                    besttarget = sum;
                }
                if (sum == target)
                    return besttarget;
                else if (sum>target)
                    n--;
                else
                    j++;
            }
        }
        return besttarget;
    }
};
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
原文地址:https://www.cnblogs.com/Scorpio989/p/4444353.html