0
点赞
收藏
分享

微信扫一扫

最接近的三数之和

RJ_Hwang 2022-04-06 阅读 94
python

 

 

 

class Solution:
    def threeSumClosest(self, nums, target):
        ret = float('inf')
        nums.sort()
        length = len(nums)
        for i in range(length - 2):
            left = i + 1
            right = length - 1
            while left < right:
                tmp = nums[i] + nums[left] + nums[right]
                ret = tmp if abs(tmp - target) < abs(ret - target) else ret
                if tmp == target:
                    return target
                if tmp > target:
                    right -= 1
                else:
                    left += 1
        return ret
class Solution:
    def threeSumClosest(self,nums,target):
        ret = float('inf')
        nums.sort()
        length = len(nums)
        for i in range(length -2):
            left =i+1
            right = length -1
            while left<right:
                tmp = nums[i] +nums[left] +nums[right]
                ret = tmp if abs[tmp-target)<abs(ret-target) else ret
                if tmp == target:
                    return target
                if tmp>target:
                    right -=1
                else:
                    left+=1
        return ret

 

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        n = len(nums)
        best = 10**7
        
        # 根据差值的绝对值来更新答案
        def update(cur):
            nonlocal best
            if abs(cur - target) < abs(best - target):
                best = cur
        
        # 枚举 a
        for i in range(n):
            # 保证和上一次枚举的元素不相等
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            # 使用双指针枚举 b 和 c
            j, k = i + 1, n - 1
            while j < k:
                s = nums[i] + nums[j] + nums[k]
                # 如果和为 target 直接返回答案
                if s == target:
                    return target
                update(s)
                if s > target:
                    # 如果和大于 target,移动 c 对应的指针
                    k0 = k - 1
                    # 移动到下一个不相等的元素
                    while j < k0 and nums[k0] == nums[k]:
                        k0 -= 1
                    k = k0
                else:
                    # 如果和小于 target,移动 b 对应的指针
                    j0 = j + 1
                    # 移动到下一个不相等的元素
                    while j0 < k and nums[j0] == nums[j]:
                        j0 += 1
                    j = j0

        return best
举报

相关推荐

0 条评论