16. 3Sum Closest

来源:互联网 发布:windows刷新英文 编辑:程序博客网 时间:2024/06/07 06:43

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

For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路:跟3sum相比,就是多了一个计算diff的过程,并记录下最小的,不需要去重。

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int ans = INT_MAX;        if (nums.size() < 3) return ans;        int ans_sum = 0;        sort(nums.begin(), nums.end());        for (int i = 0; i < nums.size() - 2; i++)        {            int sum = target - nums[i];            int m = i +1, n = nums.size() - 1;            while (m < n)            {                int diff = abs(sum - nums[m] - nums[n]);                if (diff < ans)                {                    ans = diff;                    ans_sum = nums[m] + nums[n] + nums[i];                }                if (nums[m] + nums[n] > sum)                {                    n--;                }                else if (nums[m] + nums[n] < sum)                {                    m++;                }                else                {                    return target;                }            }        }        return ans_sum;    }};
0 0