Array
016. 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.
即:
给定一个整数数组,和一个整数target,在数组中找出三个元素满足他们之和距离target最近,然后返回这三个元素的和
Solutions
和3sum那道题本质上是一样的,稍微改下就可以满足要求
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
min_num=float('inf')
nums.sort()
res=0
for i in range(len(nums)):
r,l=i+1,len(nums)-1
while r<l:
s = (nums[i] + nums[l] + nums[r])-target
if abs(s)<min_num:
min_num=abs(s)
res=s+target
if s<0:
r+=1
elif s>0:
l-=1
else:
return target
return res
网友评论