最接近的三数之和----LeetCode----(7)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_36697353/article/details/86726570

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

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

代码如下:

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()

        res = None
        i = 0

        for i in range(len(nums)):
            if i == 0 or nums[i] > nums[i-1]:
                l = i+1
                r = len(nums)-1
                while l < r:
                    s = nums[i] + nums[l] + nums[r]

                    res = s if res == None or abs(
                        s-target) < abs(res-target) else res

                    if s == target:
                        return s
                    elif s > target:
                        r -= 1
                    else:
                        l += 1
        return res
显示详情 
执行用时: 188 ms, 在3Sum Closest的Python3提交中击败了49.75% 的用户

猜你喜欢

转载自blog.csdn.net/baidu_36697353/article/details/86726570