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).

Difficulty: Medium

这道题和15. 3Sum 三数之和解法相似,只是这里需求是求三数之和的绝对值与输入的target最相近的.所以要用两个变量保存三数之和,三数之和与target的绝对值的差

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int closest = nums[0]+nums[1]+nums[2];
        int diff = abs(closest-target);
        sort(nums.begin(),nums.end());
        //循环到倒数第三个就行
        for (int i = 0;i < nums.size()-2;i++)
        {
            int left = i+1,right=nums.size()-1;
            while(left<right)
            {
                int sum = nums[i]+nums[left]+nums[right];
                int newDiff = abs(sum-target);
                if (newDiff < diff)
                {
                    diff = newDiff;
                    closest = sum;
                }
                if (sum < target) left++;
                else right--;
            }
        }
        return closest;
    }
};
 
comments powered by Disqus