leetcode-75 颜色分类
leetcode-75 颜色分类
题目描述:
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
解法一:感觉很丑
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
beg,cur,end=0,0,n-1
while cur<=end and cur<n:
while beg<n and nums[beg]%3 == 0:
beg += 1
while end>0 and nums[end]%3 == 2:
end -= 1
if nums[cur] % 3 == 0 and cur >= beg:
nums[beg], nums[cur] = nums[cur], nums[beg]
beg += 1
if nums[cur] % 3 == 2 and cur <= end:
nums[end], nums[cur] = nums[cur], nums[end]
end -= 1
if nums[cur] % 3 == 2 and cur <= end:
nums[end], nums[cur] = nums[cur], nums[end]
end -= 1
if nums[cur] % 3 == 0 and cur >= beg:
nums[beg], nums[cur] = nums[cur], nums[beg]
beg += 1
cur += 1
return nums
解法二:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
beg,cur,end=0,0,n-1
while cur <= end:
if nums[cur] == 0:
nums[beg],nums[cur] = nums[cur],nums[beg]
beg += 1
cur += 1
elif nums[cur] == 1:
cur += 1
elif nums[cur] == 2:
nums[end],nums[cur] = nums[cur],nums[end]
end -= 1