Sharing my 12ms C++ solution


  • 0
    T
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            int n = nums.size();
            int sum, minSum=INT_MAX, minDiff=INT_MAX;
            int i, left, right;
            for(i=0; i<n-2; i++)
            {
                left = i+1;
                right = n-1;
                while(left<right)
                {
                    sum = nums[i]+nums[left]+nums[right];
                    if(sum == target)
                        return sum;
                    if(abs(sum-target) < minDiff)
                    {
                        minDiff = abs(sum-target);
                        minSum = sum;
                    }
                    if(sum>target)
                        right--;
                    else
                        left++;
                }
            }
            
            return minSum; 
        }
    };

Log in to reply
 

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