LeetCode-75. 颜色分类【数组 双指针 排序】
题目描述:
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
必须在不使用库内置的 sort 函数的情况下解决这个问题。
示例 1:
输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]
示例 2:
输入:nums = [2,0,1]
输出:[0,1,2]
提示:
n == nums.length
1 <= n <= 300
nums[i] 为 0、1 或 2
进阶:
你能想出一个仅使用常数空间的一趟扫描算法吗?
解题思路一:自然而然想到双指针。一个位置指向开头0,一个位置指向末尾2。遍历一遍即可。
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def swap(nums, index1, index2):
nums[index1], nums[index2] = nums[index2], nums[index1]
n = len(nums)
if n < 2:
return
zero, two = 0, n
i = 0
while i < two:
if nums[i] == 0:
swap(nums, i, zero)
i += 1
zero += 1
elif nums[i] == 1:
i += 1
else:
two -= 1
swap(nums, i, two)
时间复杂度:O(n)
空间复杂度:O(1)
解题思路二:错误示范,这里千万不能用三个if,因为swap(nums, i, zero)的时候会改变nums从而导致下面的if可能成立!
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def swap(nums, index1, index2):
nums[index1], nums[index2] = nums[index2], nums[index1]
n = len(nums)
if n < 2:
return
zero, two = 0, n
i = 0
while i < two:
if nums[i] == 0:
swap(nums, i, zero)
i += 1
zero += 1
elif nums[i] == 1:
i += 1
elif nums[i] == 2:
two -= 1
swap(nums, i, two)
时间复杂度:O(n)
空间复杂度:O(1)
解题思路三:
时间复杂度:O(n)
空间复杂度:O(n)