版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jerry81333/article/details/76022250
3Sum Closest:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
简单来说,寻找三数之和最接近target的答案,例子如下:
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解决方法:
和 上一篇3Sum的想法类似,因此代码也是在那个的基础上修改的。只不过因为需要求最近的,而不是固定的,因此所有的判定都需要修改为判断与与target做差后的绝对值, 因为代码大构架和3Sum类似,因此时间复杂度还是O(N^2),代码如下:
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
first=[]
i=0
Max=0
while(i<len(nums)-2):
if(nums[i]!=nums[i-1] or i==0):
left=i+1
right=len(nums)-1
while(left<right):
if(abs(nums[left]+nums[right]+nums[i]-target)==0):
Max=target
break
if(i==0 and left==1 and right==len(nums)-1):
Max=nums[left]+nums[right]+nums[i]
if(abs(nums[left]+nums[right]+nums[i]-target)<abs(Max-target)):
first.append([nums[i],nums[left],nums[right]])
Max=nums[left]+nums[right]+nums[i]
while(left<right and nums[left]+nums[right]+nums[i]<target):
left+=1
if(nums[left]!=nums[left-1]):
break
while(left>right and nums[left]+nums[right]+nums[i]>target):
right-=1
if(nums[right]!=nums[right+1]):
break
elif(nums[left]+nums[right]+nums[i]>target):
right-=1
elif(nums[left]+nums[right]+nums[i]<target):
left+=1
i+=1
return Max