16.最接近的三数之和
题目
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
思路
和找三数之和没什么区别,都是用双指针减少一重循环,只不过这里多了个绝对值的考虑。
算法
1.对num进行排序
2.对nums进行遍历,记为first
3.second和third分别从左和右向中间走
4.返回结果
代码
// A code block
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
ABS= abs(target - nums[0]-nums[1]-nums[2])
res = nums[0] +nums[1] +nums[2]
for first in range(len(nums)-2):
if first>0 and nums[first] == nums[first-1]:
continue
second = first +1
third = len(nums)-1
while second <third:
if second> first+1 and nums[second] == nums[second-1]:
second += 1
continue
S = nums[first]+nums[second]+nums[third]
if S == target:
return target
if abs(target -S)< ABS:
ABS = abs(target-S)
res = S
if S>target:
third -=1
else:
second +=1
return res
执行结果
执行用时:80 ms, 在所有 Python3 提交中击败了96.14%的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了88.74%的用户
题目来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。