LeetCode 16 3Sum Closest

16. 3Sum Closest

Total Accepted: 73703 Total Submissions: 255236 Difficulty: Medium

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

Subscribe to see which companies asked this question

Have you met this question in a real interview?


和3Sum那道题差不多。

这道题要找出的三个数是和target相差最小的三个数。

裸暴力枚举会妥妥超时。

可以先排个序,从左向右,每次对枚举的结果加以判断,如果当前temp>num,说明枚举的数有些大了,把最大的数下标r--,如果temp<num,说明枚举的数有些小了,把l++;


class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target)
    {
        int ret=nums[0]+nums[1]+nums[2];
        sort(nums.begin(),nums.end());
        int len=nums.size();
        for(int i=0;i<len-2;i++)
        {
                int l=i+1,r=len-1;
                while(l<r)
                {
                        int temp=nums[i]+nums[l]+nums[r];
                        if(abs(temp-target)<abs(ret-target))
                                ret=temp;
                        if(temp>target)
                                r--;
                        else
                                l++;
                }
        }
        return ret;
    }
};


你可能感兴趣的:(LeetCode 16 3Sum Closest)