c++ 9ms solution


  • 0
    X
        int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int res=nums[0]+nums[1]+nums[2];
        for(int i=0;i<nums.size()-2;++i){
            if(i>=1 &&nums[i]==nums[i-1])
                continue;
            int j=i+1, k=nums.size()-1,sum;
            while(j<k){
                sum=nums[i]+nums[j]+nums[k];
                if(sum<target){
                    ++j;
                }
                else if(sum>target)
                    --k;
                else
                    return target;
                if(abs(sum-target)<abs(res-target))
                    res=sum;
            }
    
        }
    
    return res;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.