题解——Leetcode 16. 3Sum Closest 难度:Medium

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).
给定一个数组,需要从其中找出三个数,其和与目标值最接近,最后输出三数之和。

首先将数组按升序排序,第一个数从开始遍历数组直到倒数第三位,第二个数从第一个数后面一位开始遍历,第三个数从数组末尾开始遍历。

当第二个数遍历未超过第三个数时,比较现有三数之和sum和目标值的大小,若相等,则返回sum,如果sum大,则第三个数左移一位,如果目标值大,则第二个数右移一位(数组升序排列)。最后比较sum和closest哪个更接近目标值,如果sum更接近,则将sum赋值给closest。

当第一个数遍历结束,便得到了最接近目标值的closest。

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int closest = nums[0] + nums[1] + nums[2]; 
        
        for(int i = 0; i < nums.size() - 2; i++){
            int front = i + 1, end = nums.size() - 1;
            
            while(front < end){
                int sum = nums[i] + nums[front] + nums[end];
                if(abs(sum - target) < abs(closest - target))
                    closest = sum;
                if(sum == target)
                    return sum;
                if(sum > target)
                    end--;
                if(sum < target)
                    front++;
            }
        }
        return closest;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值