【每日一题】leetcode16. 最接近的三数之和

【每日一题】leetcode16. 最接近的三数之和_第1张图片
双指针法

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

            }
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode)