1. 程式人生 > >leetcode-16:3sum closest最近的三數之和

leetcode-16:3sum closest最近的三數之和

題目:

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

給定一個包括 n 個整數的陣列 nums 和 一個目標值 target。找出 nums 中的三個整數,使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。

例如,給定陣列 nums = [-1,2,1,-4], 和 target = 1.

與 target 最接近的三個數的和為 2. (-1 + 2 + 1 = 2).

思路:和上一題類似,要保證和target的差 最小,那麼定義 一個變數diff儲存他們之間的差。首先排序,然後固定一個位置,剩下的兩個數left從左往右,right從又往左,每確定兩個數,我們求出此三數之和,然後算和給定值的差的絕對值存在newDiff中,然後和diff比較並更新diff和結果closest即可

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;
    }
};

參考:http://www.cnblogs.com/grandyang/p/4510984.html