当前位置: 代码迷 >> 综合 >> leetcode刷题-16_3Sum Closest
  详细解决方案

leetcode刷题-16_3Sum Closest

热度:44   发布时间:2024-02-08 17:24:44.0

东阳的学习记录,坚持就是胜利!

暴力法

暴力法依旧超时,其实这题和15题几乎一模一样,就不写了

从两端逼近

同样是两边向中间逼近的方法,和15题没有太大的区别

class Solution:def threeSumClosest(self, nums: list, target: int) -> int:nums.sort()# print(nums)closest = nums[0] + nums[1] + nums[2]diff = abs(closest - target)for i in range(0, len(nums) - 2):low, high = i + 1, len(nums)-1while low < high:sums = nums[low] + nums[high] + nums[i]new_diff = abs(sums - target)if new_diff < diff:diff = new_diffclosest = sums  if sums < target:low += 1else:high -= 1return closest

暂时不知道怎么改进