Leetcode's closest sum of three numbers c++

The nearest sum of three numbers

Given an array of n integers nums and a target value target. Find the three integers in nums so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs.

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

Solution 1: Violence

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        if(nums.size()<3) return {};
        int closest=target+10000000;
        for(int i=0;i<nums.size()-2;i++)
        {
            int fix=nums[i];
            if(fix>target&&abs(fix+nums[i+1]+nums[i+2]-target)>abs(closest-target)) break;
            //这句话能够省略很多无用功
            for(int j=i+1;j<nums.size()-1;j++)
            {
                for(int k=j+1;k<nums.size();k++)
                {
                    int temp=abs(target-fix-nums[j]-nums[k]);
                    if(temp<abs(closest-target))
                        closest=fix+nums[j]+nums[k];
                }
            }
        }
        return closest;
    }
};

Solution 2: Double pointer method (collision pointer)

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        if(nums.size()<3)
            return {};
        int closest=target+1000000;
        int cha=0;
        for(int i=0;i<nums.size();i++)
        {
            int fix=nums[i];
            int l=i+1;
            int r=nums.size()-1;
            if(l>=r) break;
            while(l<r)
            {
                if(nums[l]+nums[r]+fix==target) return target;
                if(nums[l]+nums[r]<target-fix)
                {
                    cha=target-fix-nums[r]-nums[l];
                    if(cha<abs(closest-target))
                        closest=nums[l]+nums[r]+fix;
                    l++;
                }
                else if(nums[l]+nums[r]>target-fix)
                {
                    cha=nums[l]+nums[r]+fix-target;
                    if(cha<abs(closest-target))
                        closest=nums[l]+nums[r]+fix;
                    r--;
                }
            }
        }
        return closest;
    }
};

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/90264179