Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
N sum系列。寻找与目标最相近的三数之和。
因为不用处理重复的问题,所以这道题反而更简单点
要注意的是在求和的值与目标相等时,就可以直接返回了
1 class Solution: 2 def threeSumClosest(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 nums.sort() 9 result = None 10 for i in range(len(nums)-2): 11 if i > 0 and nums[i] == nums[i-1]: 12 continue 13 left, right = i + 1, len(nums) - 1 14 while left < right : 15 s = nums[i] + nums[left] + nums[right] 16 if result is None or abs(s - target) < abs(result - target) : 17 result = s 18 if s < target : 19 left += 1 20 elif s > target : 21 right -= 1 22 else : 23 return target 24 return result