3Sum Closest

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
       
        int len = nums.size();
        int ans = 0x3FFFFFFF;
        int res = 0;
        for(int i = 0 ; i < len ; i ++)
        {
            int left = i + 1;
            int right = len - 1;
            while(left < right)
            {
                int key = nums[left] + nums[right] + nums[i];
                if( key < target ){
                    left ++;
                }else if( key > target ){
                    right --;
                }else
                    return target;
                int fc = abs(key-target);
                if( fc < ans )
                {
                    ans = fc;
                    res = key;
                }
            }
           
        }
        return res;
       
    }
};

原文地址:https://www.cnblogs.com/clover-xuqi/p/8323632.html