Leetcode 16. 3Sum Closest
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变成0,然后将数组分为正负两个数组然后三个一起加暴力解法看与0的距离,代码如下:
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if(len(nums) <= 3):
return sum(nums)
divideTarget = target*1.0/3
for i in range(len(nums)):
nums[i] -= divideTarget
nums = sorted(nums)
if(nums[0] >= 0):
result = nums[0]+nums[1]+nums[2]
return int(round(result+target))
if(nums[len(nums)-1] <= 0):
result = nums[-1]+nums[-2]+nums[-3]
return int(round(result+target))
index = 0
for index in range(len(nums)):
if nums[index]>=0:
break
NegNums = nums[0:index]
PosNums = nums[index:]
minSum = float('inf')
result = target
for i in range(len(NegNums)):
for j in range(len(NegNums)):
if(i < j):
val = -(NegNums[i]+NegNums[j])
else:
continue
for pos in PosNums:
if val == pos:
return target
curVal = max(val, pos)-min(val,pos)
if(minSum > curVal):
minSum = curVal
result = -val + pos + target
for i in range(len(PosNums)):
for j in range(len(PosNums)):
if(i < j):
val = PosNums[i]+PosNums[j]
else:
continue
for neg in NegNums:
if val == -neg:
return target
curVal = max(val, -neg)-min(val,-neg)
if curVal < minSum:
minSum = curVal
result = val + neg + target
return int(round(result))
此处注意在最后返回的时候需要进行float转int,但是int是直接截断所以返回了int(round(result))
超时了。
发现在尽管做了分割在最差的状况下它的时间复杂度为O(n^3/8)+O(nlog(n))
我觉得可以考虑双指针从0的边缘处找数值,有点复杂可能之后有时间再写。
看了别人的双指针解法之后发现自己想复杂了,用双指针就能够解。代码如下:
def threeSumClosest(nums, target):
nums.sort()
min_gap, n = float('inf'), len(nums)
for i in range(n-2):
head, l, r = nums[i], i+1, n-1
while l < r:
gap = head+nums[l]+nums[r] - target
min_gap = min(min_gap, gap, key=abs)
if gap < 0: l += 1
elif gap > 0: r -= 1
else: return target
return target + min_gap