1. 程式人生 > >leetcode 3 sum closest

leetcode 3 sum closest

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

注意left < right 的限制