Leetcode16_【最接近的三数之和】

文章目录:

  • 题目
  • 脚本一
  • 脚本一逻辑

题目:

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

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

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


脚本一:【用时:96ms】

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        k = 0
        result = nums[0] + nums[1] + nums[2]
        result2 = abs(nums[0] + nums[1] + nums[2] -target)
        for k in range(len(nums) - 2):
            if k > 0 and nums[k] == nums[k - 1]: continue 
            i, j = k + 1, len(nums) - 1
            while i < j: # 3. double pointer
                s = nums[k] + nums[i] + nums[j]
                result1 = s - target
                result3 = abs(result1)
                if result2 >= result3:
                    result2 = result3
                    result = s
                if result1 < 0:
                    i += 1
                    while i < j and nums[i] == nums[i - 1]: i += 1
                elif result1 > 0:
                    j -= 1
                    while i < j and nums[j] == nums[j + 1]: j -= 1
                else:
                    return(result)
                    i += 1
                    j -= 1
                    while i < j and nums[i] == nums[i - 1]: i += 1
                    while i < j and nums[j] == nums[j + 1]: j -= 1
        return(result)

脚本一逻辑:

  • 依然是采用上一题的解法思路,对所有组合进行遍历,在遍历过程中,对重复项进行处理
  • 与上一题有些不一样的地方是,此题是最接近的数,不是特定值
  • 此题主要采用了双指针的方式进行遍历求解
  • 采用了排序后的前三个元素作为初始值进行遍历比较

猜你喜欢

转载自www.cnblogs.com/mailong/p/12026467.html