12ms c++ solution


  • 0
    B
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int result;
            int n = nums.size();
        
            sort(nums.begin(), nums.end());
            int minDistance = INT_MAX;
            int j = 0;
            while (j < n-2)
            {
                if (j > 0 && nums[j] == nums[j-1])
                {
                    j++;
                    continue;
                }
    
                int sum = target - nums[j];
                int left = j+1;
                int right = n-1;
                while (left < right)
                {
                    int value = nums[left] + nums[right];
                    if (sum == value)
                    {
                        return target;
                    }
                    else if (value > sum)
                    {
                        if (value-sum < minDistance)
                        {
                            minDistance = value-sum;
                            result = nums[j] + value;
                        }
                        right--;
                        while (right > left && nums[right] == nums[right+1])
                        {
                            right--;
                        }
                    }
                    else
                    {
                        if (sum-value < minDistance)
                        {
                            minDistance = sum-value;
                            result = nums[j] + value;
                        }
                        left++;
                        while (left < right && nums[left] == nums[left-1])
                        {
                            left++;
                        }
                    }
                }
                j++;
            }
    
            return result;
        }
    };

  • 0
    S

    Do you kown the code which runtime is 8ms? Thanks


Log in to reply
 

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