leetcode 16 3Sum Closest

2018-06-04 12:28:12 浏览数 (1)

代码语言:javascript复制
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int closest = nums[0]   nums[1]   nums[2];
        int diff = abs(closest - target);
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 2;   i) {
            int left = i   1, right = nums.size() - 1;
            while (left < right) {
                int sum = nums[i]   nums[left]   nums[right];
                int newDiff = abs(sum - target);
                if (diff > newDiff) {
                    diff = newDiff;
                    closest = sum;
                }
                if (sum < target)   left;
                else --right;
            }
        }
        return closest;
    }
};

0 人点赞