东阳的学习记录,坚持就是胜利!
暴力法
暴力法依旧超时,其实这题和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