16. 最接近的三数之和

Medium

思路

看到三数之和,想到15.三数之和,这道题可以在三数之和的基础上思考。

接下来就能写出代码了,AC!

代码

python3

class Solution:
  def threeSumClosest(self, nums: List[int], target: int) -> int:
    nums.sort()
    result = math.inf
    for i in range(len(nums)):
      j = i + 1
      k = len(nums) - 1
      while j < k:
        s = nums[i] + nums[j] + nums[k]
        if s == target:
          return s
        if s > target:
          k -= 1
        else:
          j += 1
        if abs(target-s) <= abs(target-result):
          result = s
    return result