「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」
[三数之和]
难度:中等
给你一个包含 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
分析过程:
- 判断是否少于三个数据,少于直接返回[]
- 排序,遍历,固定第一个数,然后对后两个数据进行两数运算
- 判断是否有重复,不重复就放入结果池中 return res
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3 :return []
nums = sorted(nums)
res = []
for first_idx in range(len(nums)): # 固定第一个数
if first_idx > 0 and nums[first_idx] == nums[first_idx-1]: # 跳过第一个数重复的元素
continue
subres = self.twoSum(nums[first_idx+1:], 0-nums[first_idx]) # 解决twoSum问题,返回的是二元组列表
for i in range(len(subres)): # 合并结果
res.append([nums[first_idx]]+subres[i])
return res
def twoSum(self, nums, target):
left, right = 0, len(nums)-1
res = []
while left < right:
if nums[left] + nums[right] == target:
res.append([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 nums[left] + nums[right] > target:
right -= 1
else:
left += 1
return res
执行结果:
[颜色分类]
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
示例 1:
输入:nums = [2,0,2,1,1,0] 输出:[0,0,1,1,2,2] 示例 2:
输入:nums = [2,0,1] 输出:[0,1,2] 示例 3:
输入:nums = [0] 输出:[0] 示例 4:
输入:nums = [1] 输出:[1]
提示:
n == nums.length 1 <= n <= 300 nums[i] 为 0、1 或 2 进阶:
你可以不使用代码库中的排序函数来解决这道题吗? 你能想出一个仅使用常数空间的一趟扫描算法吗?
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
for row in range(n):
for j in range(row+1,n):
if nums[row] >nums[j]:
nums[row],nums[j] = nums[j],nums[row]
return nums