Study Plan For Algorithms - Part8
1. 三数之和
给定一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。返回所有和为 0 且不重复的三元组。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return res
2. 最接近的三数之和
给定一个长度为 n 的整数数组 nums 和 一个目标值 target。请从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
closest_sum = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
left = i + 1
right = len(nums) - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
if current_sum < target:
left += 1
elif current_sum > target:
right -= 1
else:
return target
return closest_sum
本文来自博客园,作者:WindMay,转载请注明原文链接:https://www.cnblogs.com/stephenxiong001/p/18374833