弟中弟的Leetcode总结——数组类(六)
题目描述
3Sum Closest
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).
思路
和前面做过的3Sum问题类似,还是设置两个指针,然后这次判断的条件不是sum==target,而是sum-taget的绝对值的大小。同理移动的时候判断sum-target的正负,如果小于0则移动前面的指针,否则移动后面的。
代码
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
sub=10000000
value=0
nums.sort()
leng=len(nums)
for i in range(leng):
begin=i+1
end=leng-1
while(begin<end):
noob=abs(nums[i]+nums[begin]+nums[end]-target)
if(noob==0):
return target
if(noob<sub):
sub=noob
value=nums[i]+nums[begin]+nums[end]
if(nums[i]+nums[begin]+nums[end]-target<0):
begin=begin+1
elif(nums[i]+nums[begin]+nums[end]-target>0):
end=end-1
return value