您的位置:首页 > 其它

Leetcode=最接近的三数之和

2019-02-02 16:24 323 查看

Leetcode=最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

解决方法:类似题库14三数之和的方法,先排序,然后遍历数组,找另外两个数left和right,判断三数之和和target的距离,如果小就left++,如果大就right–。

class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
length = len(nums)
min_val = float("inf")
res = 0
for i in range(length - 2):
l = i + 1
r = length - 1
while l < r:
sum_val = nums[i] + nums[l] + nums[r]
if sum_val - target == 0:
return target
if abs(sum_val - target) < min_val:
min_val = abs(nums[i] + nums[l] + nums[r] - target)
res = sum_val
if sum_val > target:
r -= 1
else:
l += 1
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: