[leetcode] 【数组】16. 3Sum Closest

来源:互联网 发布:酒店前台收银软件 编辑:程序博客网 时间:2024/06/05 06:19

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

题解

题意和3 sum类似,这里区别是取和target最近的组合,返回组合的和值。
a遍历三遍;
b排序+夹逼:

//cppclass Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        sort(nums.begin(),nums.end());        int res=0;        auto tail=nums.end();        int min_closet=INT_MAX;        for(auto a=nums.begin();a!=tail-2;a++)        {            if(*a==*(a-1)&&a!=nums.begin())                continue;            auto b=a+1;            auto c=tail-1;            while(b<c)            {                int sum=*a+*b+*c;                int closet=abs(target-sum);                if(closet<min_closet)                {                    res=sum;                    min_closet=closet;                    if(closet==0) return res;                }                if(sum<target)                    b++;                else c--;            }        }        return res;    }};
0 0