这道题与15. 3Sum的思路完全一样,先对数组排序,然后固定住第一个数,用2 pointer查找其余的两个数。
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
head = i + 1
tail = len(nums) - 1
while head < tail:
total = nums[i] + nums[head] + nums[tail]
if total == target:
return target
elif total < target:
head += 1
else:
tail -= 1
if abs(total - target) < abs(result - target):
result = total
return result