leetcode 15 三数之和 16 最接近的三数之和
15. 三数之和
难度中等3358收藏分享切换为英文接收动态反馈
给你一个包含 n
个整数的数组 nums
,判断 nums
中是否存在三个元素 *a,b,c ,*使得 a + b + c = 0 ?请你找出所有和为 0
且不重复的三元组。
**注意:**答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
arr = []
nums.sort()
i,l = 0,len(nums)
for i in range(l):
if i > 0 and nums[i] == nums[i-1]:
continue
j = l - 1
target = -nums[i]
for s in range(i+1,j):
if s > i + 1 and nums[s] == nums[s - 1]:
continue
while s < j and nums[s] + nums[j] > target:
j -= 1
if s == j:
break
if nums[s] + nums[j] == target:
arr.append([nums[i], nums[s], nums[j]])
return arr
#[-5, -5, -4, -4, -4, -3, -2, -1, -1, 1, 2, 2]
if __name__ == '__main__':
a = [-5,-1,-5,-4,2,1,-1,2,-4,-3,-2,-4]
b = [-2,-3,0,0,-2,1,1]
d = [0,0,0,0]
print(Solution().threeSum(d))
16. 最接近的三数之和
难度中等779收藏分享切换为英文接收动态反馈
给定一个包括 n 个整数的数组 nums
和 一个目标值 target
。找出 nums
中的三个整数,使得它们的和与 target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
nlen = len(nums)
ans = nums[0] + nums[1] + nums[2]
def update(cur):
nonlocal ans
if abs(target - cur) < abs(target - ans):
ans = cur
for i in range(nlen-2):
right = nlen - 1
left = i + 1
while right > left:
s = nums[i] + nums[left] + nums[right]
if s == target:
return s
update(s)
if s >= target:
right -= 1
else:
left += 1
return ans