首页 > 代码库 > 最接近的三数之和

最接近的三数之和

代码:

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;

    }

};

lintcode截图:

技术分享

 

最接近的三数之和