12ms C++ two pointers solution


  • 0
    H

    '''
    class Solution {
    public:
    int threeSumClosest(vector<int>& nums, int target) {
    int Ns = nums.size();
    sort(nums.begin(), nums.end());
    int minDiff = INT_MAX;
    for(int i = 0; i < Ns; i++){
    int tar = target - nums[i];
    int left = i + 1;
    int right = Ns - 1;

            while(left < right){
                 int diffs = nums[left] + nums[right] - tar;
                if(diffs == 0) return target;
                else if(diffs < 0 ){
                    left++;
                    if(abs(diffs) < abs(minDiff)) minDiff = diffs; 
                }
                else{
                    right--;
                     if(abs(diffs) < abs(minDiff)) minDiff = diffs; 
                }
            }
            
        }
      return target+minDiff;   
    }
    

    };
    '''


Log in to reply
 

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