问题描述
Given an array nums of n integers and an integer target, find three integers 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.
例子
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
2019-06-04
类3Sum
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
L = len(nums)
result = float('inf')
res = []
for i in range(L):
left, right = i+1, L - 1
while left < right:
summation = nums[i]+nums[left]+nums[right]
if abs(summation-target) <= abs(result-target):
result = summation
res = [nums[i],nums[left],nums[right]]
if summation < target:
left = left + 1 #注意这里与3Sum中的差别
elif summation > target:
right = right - 1#注意这里与3Sum中的差别
else:
return target
return result
结果分析
Runtime: 100 ms, faster than 64.41% of Python online submissions for 3Sum Closest.
Memory Usage: 11.8 MB, less than 29.26% of Python online submissions for 3Sum Closest.
注意到题目中描述为,你可以假设对于任意输入只有唯一解。什么含义呢?就是在测试中,不会出现重复数字。所以与3Sum
中不同的是,不需要判断前后两数是否相同后移/前移指针等操作。