LeetCode:16. 3Sum Closest

LeetCode: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.
Example:

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

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

题目的意思就是给出一串整型数字,以及一个目标值,求这串数字中三个数字之和最接近目标值的情况,输出这个和。

思路:从中心向两侧扩展

这一题有点类似于LeetCode:15. 3Sum,只不过第15题是求出和为0的情况。我们还是使用相同的思路,从中心向两侧扩展。如果发现三个数字之和与目标值的差值小于0,则右侧数字向右移动,否则左侧数字向左移动。

Python 代码实现

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        sortNums = sorted(nums)
        print(sortNums)
        l = len(sortNums)
        
        res = 0
    
        minDx = 2147483647 # 最小差距
        # 从中心向两边扩展
        center = 1
        toRightFlag = True # True:right+=1 ; False:left-=1
        for center in range(l-1):
            left = center -1 
            right = center + 1
            
            while left >= 0 and right < l:
                tmpSum = sortNums[left]+sortNums[center]+sortNums[right]
                tmpDx = tmpSum - target
    
                if tmpDx == 0:
                    if abs(tmpDx) < minDx:
                        print("=0",minDx,abs(tmpDx) , tmpSum)
                        minDx = abs(tmpDx)
                        res = tmpSum
                    if toRightFlag:
                        right = right + 1
                    else:
                        left = left -1
  
                if tmpDx < 0:
                    if abs(tmpDx) < minDx:
                        print("<0",minDx,abs(tmpDx) , tmpSum)
                        minDx = abs(tmpDx)
                        res = tmpSum
                    right = right + 1
                    toRightFlag = True
                    
                if tmpDx > 0:
                    if abs(tmpDx) < minDx:
                        print(">0",minDx,abs(tmpDx) , tmpSum)
                        minDx = abs(tmpDx)
                        res = tmpSum
                    left = left -1
                    toRightFlag = False

        return res          

THE END.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值