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;
       
    }
};

posted on 2018-01-21 10:49  朽木の半夏  阅读(92)  评论(0编辑  收藏  举报