[leetcode刷题系列]3Sum Closest

- - 开始写模糊了- n^2复杂度


class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(num.size() < 3)
            return 0;
        sort(num.begin(), num.end());
        int ans = num[0] + num[1] + num[2];
        for(int i = 0; i + 2< num.size(); ++ i){
            int p = num.size() - 1;
            for(int j = i + 1; j + 1 < num.size() && j < p; ++ j){
                while(p > j)
                    if(num[i] + num[j] + num[p] >= target)
                        --p;
                    else
                        break;
                // less
                if(p + 1 < num.size()){
                    if(abs(num[i] + num[j] + num[p + 1] - target) < abs(ans - target))
                        ans = num[i] + num[j] + num[p + 1];
                }
                if(p > j){
                    if(abs(num[i] + num[j] + num[p] - target) < abs(ans - target))
                        ans = num[i] + num[j] + num[p];
                }
            }
        }
        return ans;
    }
};


你可能感兴趣的:([leetcode刷题系列]3Sum Closest)