[Leetcode] 16 - 3Sum Closest

原题链接:https://oj.leetcode.com/problems/3sum-closest/


这道题基本就是3sum的变形,就直接按照3sum先排序,然后取当前数,再左右指针对于后面的数组向内扫描,但是因为是求closest,只有diff = 0的时候才能完全跳出当前循环,否则则需要继续扫描直到相遇或diff = 0。


所以复杂度是排序时间加上扫描时间O(nlogn + n^2)


class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int diff = INT_MAX;
        int res = 0;
        sort(num.begin(), num.end());
        
        for (int i = 0; i < num.size() - 2; ++i) {
            int left = i + 1;
            int right = num.size() - 1;
            
            while (left < right) {
                int curSum = num[i] + num[left] + num[right];
                if (curSum == target) {
                    return curSum;
                } else if (curSum > target) {
                    if (abs(curSum - target) < diff) {
                        diff = abs(curSum - target);
                        res = curSum;
                    }
                    --right;
                } else {
                    if (abs(curSum - target) < diff) {
                        diff = abs(curSum - target);
                        res = curSum;
                    }
                    ++left;
                }
            }
        }
        
        return res;
    }
};




你可能感兴趣的:([Leetcode] 16 - 3Sum Closest)