题目描述:
题解:
def threeSumClosest(self, nums, target): lennum = len(nums) gap = float("inf") clossum = float("inf") for i in range(lennum): for j in range(i+1,lennum): for k in range(j+1,lennum): sum = nums[i]+nums[j]+nums[k] tmpgap = abs(sum-target) if tmpgap<gap: gap = tmpgap clossum = sum return clossum
利用三个for循环分别在输入数组中选择三个元素,计算3个数之和,计算与target的差值,返回最小差值对应的和。
通过,没有超时。
但是参考https://blog.csdn.net/fuxuemingzhu/article/details/83116781的更简单的方法:
也采用了双指针,和之前的一道题很像。对输入数组排序后,进行遍历,当遍历到nums[i]时,设置指针j=i+1 k=len(nums)-1,计算nums[i] nums[j] nums[k]之和,计算与target之差,若小于当前的差值,则更新,若三数之和大于target则k-1,否则j+1
def threeSumClosest(self, nums, target):
lennums = len(nums)
finsum = float("inf")
fingap = float("inf")
nums.sort()
for i in range(lennums):
j = i+1
k = lennums-1
while j<k:
tmpsum = nums[i]+nums[j]+nums[k]
tmpgap = abs(tmpsum-target)
if tmpgap<fingap:
fingap = tmpgap
finsum = tmpsum
if tmpsum>target:
k = k-1
else:
j = j+1
return finsum