LeetCode 16. 3Sum Closest

题目

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).

题意

给出一个数组和一个target,在这个数组中找出和最接近target的三个数。比如:

给出数组 S = {-1 2 1 -4},  target = 1.

最接近target的和为 2. (-1 + 2 + 1 = 2).

分析

这道题可以用深度搜索,考虑到深度只为3,我做了简化。

首先选定第一个数one,那么剩下的两个数two、three符合条件,one+two+three ~ target。

考虑到two和three是数组中不同下标的值,可以分别从给出数组头和尾部往中间找。这样一来,时间复杂度从 O(n^3) 降为 O(n*n)。

思路
1、首先先对数组进行排序处理。
2、对 result 进行初始化赋值
3、for 循环选择,得到第一个数字one。
4、从数字两端向中间靠拢找的two、three。
5、curr 等于当前的 one+two+three。

  • A. 如果curr更接近target,result = curr。
  • B. 如果curr 小于 target,two向后移一位。
  • C.如果curr 大于 target,three向前移一位。
  • D.如果curr 等于 target,那么正好,找到了最接近target的值,可以直接返回了。

代码

int threeSumClosest(vector<int>& nums,int target) {
    int result = 0;
    std::sort(nums.begin(), nums.end());
    for(int i=0;i<nums.size()&&i<3;i++)
        result+=nums[i];
    for(int one=0;one<nums.size()-2;one++){
        int two=one+1, three =nums.size()-1;
        while(two<three){
            int curr = nums[one]+nums[two]+nums[three];
            if(abs(curr-target)<abs(result-target))
                result = curr;
            if(curr>target)
                three--;
            else if(curr<target)
                two++;
            else if(curr==target)
                return target;
        }

    }
    return result;
}

125 / 125 test cases passed.
Runtime: 12 ms

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值