原题目
Given an array
nums
of n integers and an integertarget
, find three integers innums
such that the sum is closest totarget
. Return the sum of the three integers. You may assume that each input would have exactly one solution.Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路
和上面三数之和思路相同,这里设置一个最小值用来比较,当三数之和不是恰好等于 target 的时候就返回最小值对应的和。
第一遍解法
# Runtime: 76 ms, faster than 96.19% of Python3
# Memory Usage: 13.2 MB, less than 52.66% of Python3
class Solution:
def threeSumClosest(self, nums, target):
nums.sort()
min = 100000
ans = -1
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
low, high = i+1, len(nums)-1
while low < high:
sum = nums[i] + nums[low] + nums[high]
if sum < target:
if target-sum < min:
min = target - sum
ans = sum
low += 1
elif sum > target:
if sum-target < min:
min = sum - target
ans = sum
high -= 1
else:
ans = sum
return ans
return ans
网上好的解法
class Solution:
# @return an integer
def threeSumClosest(self, num, target):
num.sort()
result = num[0] + num[1] + num[2]
for i in range(len(num) - 2):
j, k = i+1, len(num) - 1
while j < k:
sum = num[i] + num[j] + num[k]
if sum == target:
return sum
if abs(sum - target) < abs(result - target):
result = sum
if sum < target:
j += 1
elif sum > target:
k -= 1
return result
自己可以改进的地方
- 不用设置 min 而是直接用任意三数之和
- 相等时直接返回,其他两种情况 sum 和 target 更接近时 ans 最后都是等于 sum,不用分别赋值
最简代码
class Solution:
def threeSumClosest(self, nums, target):
if len(nums) < 3:
return -1
nums.sort()
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
low, high = i+1, len(nums)-1
while low < high:
sum = nums[i] + nums[low] + nums[high]
if abs(sum-target) < abs(result-target):
result = sum
if sum < target:
low += 1
elif sum > target:
high -= 1
else:
return target
return result
获得的思考
- 将重复的代码合并使程序更简洁,可读性更高