16. 3Sum Closest

【题目】

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

【举例】

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

【题目翻译】

给定一个数组和一个target, 在该数组里找和最接近target的三元组, 返回它的和。

【解题思路】

一开始我想着用回溯法解决这个问题, 遍历所有可能的三元组, 在这个过程中记录最接近的和。

写完代码以后发现运行超时。

 

然后我们发现可以用解决三和问题的通用解法:

首先假设最接近的和是result=nums[0] + nums[1] + nums[len(nums)-1](ps:初始值一般尽可能设为最开始判断的三元组)

然后遍历所有可能的起点i, 用双指针指向剩余元素里面的第一个元素i+1, 和最后一个元素len(nums)-1

判断当前三元组的和sum_是否更接近target, 如果是, 更新一下result

然后判断如果sum_ < target, lo += 1

否则hi -= 1

 

在遍历起点的时候, 如果该起点nums[i] == nums[i-1], 那么该起点的情况就不用再考虑, 因为, 该起点能找到的最接近的和, 已经包括在上一个起点之中。

【代码实现】

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        result = nums[0] + nums[1] + nums[len(nums)-1] 
        for i in range(len(nums)-2):
            if i == 0 or nums[i] != nums[i-1]: #如果当前起点元素等于前面一个元素, 不用判断
                lo = i + 1
                hi = len(nums) - 1
                while lo < hi:
                    sum_ = nums[i] + nums[lo] + nums[hi]
                    #当前和更接近target, 更新result的值
                    result = sum_ if abs(sum_ - target) < abs(result - target) else result 
                    if sum_ < target:
                        lo += 1
                    else:
                        hi -= 1
        return result

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值