LeetCode: 3Sum Closest

思路:和上一题的3 sum思路一样,只是记录最接近的和即可。

code:

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(),num.end());
        int ret = INT_MAX,sum = 0;
        for(int i = 0; i<num.size();i++){
            int j = i+1, k = num.size()-1;
            while(j < k){
                if(ret > abs(num[i] + num[j] + num[k] - target)){
                    sum = num[i] + num[j] + num[k];
                    ret = abs(num[i] + num[j] + num[k] - target);
                }
                if(num[i] + num[j] + num[k] < target)
                    j++;
                else if(num[i] + num[j] + num[k] > target)
                    k--;
                else
                    return target;
            }
        }
        return sum;
    }
};


你可能感兴趣的:(LeetCode: 3Sum Closest)