16. 最接近的三数之和

题目描述

 给定一个包括 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 
posted @ 2021-02-16 23:42  Bladers  阅读(46)  评论(0)    收藏  举报