首页 > 其他 > 详细

16. 最接近的三数之和

时间:2021-02-17 10:39:28      阅读:23      评论:0      收藏:0      [点我收藏+]

题目描述

?给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

原题请参考链接https://leetcode-cn.com/problems/3sum-closest/

题解

方法一?【排序+双指针】

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        l = len(nums)
        res =  10**7
        nums.sort()
        for a in range(l):
            if a>0 and nums[a] == nums[a-1]:
               continue
            b = a + 1
            c = l - 1
            while b < c :
                s = nums[a] + nums[b] + nums[c]
                if s == target:
                    return s
                if abs(s-target) < abs(res-target):
                    res = s
                if s > target:
                    c0 = c - 1
                    while b < c0 and nums[c0] == nums[c]:
                        c0 -= 1
                    c = c0
                if s < target:
                    b0 = b + 1
                    while b0<c and nums[b0] == nums[b]:
                        b0 += 1
                    b = b0
        return res 

16. 最接近的三数之和

原文:https://www.cnblogs.com/bladers/p/14407948.html

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