LeetCode 16 最接近的三数之和

LeetCode 16 最接近的三数之和

🟡 中等 https://leetcode.cn/problems/3sum-closest/description/

类似三数之和。

先排序,确定一个数后使用双指针。

class Solution {

public:

    int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(),nums.end());

        int n = nums.size();

        long best = INT_MAX;

        int i = 0;

        while(i<n){

            int left = i+1,right = n-1;

            while(left<right&&best!=target){

                long sum = nums[i]+nums[left]+nums[right];

                if(sum>target){

                    right--;

                }

                if(sum<target){

                    left++;

                }

                best = abs(sum-target)<abs(best-target)?sum:best;

                // cout<<i<<left<<right<<best<<endl;

            }

            i++;

        }

        return best;

    }

};