首页 > 其他 > 详细

最接近的三数之和

时间:2019-09-17 23:56:31      阅读:121      评论:0      收藏:0      [点我收藏+]

思路:跟三数之和的思路相同,只不过这里是最接近target的三个数,同样将数组排序,固定第一个数,后面两个数用双指针移动,当三个数的和大于target,那么将右边指针左移,如果三个数的和小于target,那么将左边指针右移。

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        min_value = 1000000
        for k in range(len(nums)-2):
            i = k+1
            j = len(nums)-1
            
            while i < j:
                s = nums[k] + nums[i] + nums[j]
                if s == target:
                    return target
                elif s < target:
                    if target-s < min_value:
                        min_value = target-s
                        res = s
                    i += 1
                else:
                    if s-target < min_value:
                        min_value = s-target
                        res = s
                    j -= 1
        return res
                    
                

最接近的三数之和

原文:https://www.cnblogs.com/dolisun/p/11537783.html

(3)
(3)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!