美文网首页
[leetcode] 16. 3Sum Closest

[leetcode] 16. 3Sum Closest

作者: 叶孤陈 | 来源:发表于2017-06-05 20:07 被阅读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;
        }
    };
    

    相关文章

      网友评论

          本文标题:[leetcode] 16. 3Sum Closest

          本文链接:https://www.haomeiwen.com/subject/xdlwfxtx.html