Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Code language: HTTP (http)
Example 2:
Input: nums = [0,0,0], target = 1
Output: 0
Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
Code language: HTTP (http)
基本上是同一个思路,只是closet主要是要计算出一个最接近的值,还有一个比较难想通的地方是,双指针怎么移动和需要return的result没关系,需要单独移动。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
diff = float("inf")
res = 0
nums.sort()
for i, n in enumerate(nums):
t = target - n
left = i + 1
right = len(nums) -1
while left < right:
curr = nums[left] + nums[right]
if abs(nums[left] + nums[right] - t) < diff:
diff = abs(nums[left] + nums[right] - t)
res = nums[left] + nums[right] + n
# 决定双指针怎么移动
if curr < t:
left += 1
elif curr > t:
right -= 1
else:
return res
return res
Python
文章评论