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.
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
我大致看了下解答和我的思路差不多,为什么我写出来的代码,体积大运行时间还慢呢?
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
d1=nums[0]+nums[1]+nums[-1]-target
for i in range(len(nums)-2):
start=i+1
end=len(nums)-1
flag=float(“inf”)
while end>start:
d=nums[i]+nums[start]+nums[end]-target
if abs(d)<abs(d1):
d1=d
if d>=0:
end -=1
if d<0:
start +=1
return d1+target