[leetcode] 16. 3Sum Closest

2017-06-05  本文已影响0人  叶孤陈

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.

Example

    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的变种题,基本思路一致。代码如下:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int number = nums.size();
        int res = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < number - 2; ++i)
        {
            int l = i + 1, r = number - 1;
            while(l < r)
            {
                int num = nums[i] + nums[l] + nums[r];
                if(abs(num - target) < abs(res - target))
                    res = num;
                
                if(num < target)
                    l++;
                else
                    r--;
            }
        }
        return res;
    }
};
上一篇下一篇

猜你喜欢

热点阅读