给定一个包含红色、白色和蓝色、共
n个元素的数组nums,**原地**对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数
0、1和2分别表示红色、白色和蓝色。必须在不使用库内置的 sort 函数的情况下解决这个问题。
题目要求不能排序,那想到的方法只能是双指针的方法,可以仿照之前的思路,使用快慢指针。时间复杂度3n。
python
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if not nums:
return
def points_type(nums, k):
slow = 0
for fast in range(len(nums)):
if nums[fast] != k:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
colors = [0, 1, 2]
for color in colors:
points_type(nums, color)
这里使用时间复杂度为On的进行1次遍历,主要确定0/2的位置完整的话,1的位置也是完整的。
python
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if not nums:
return
left = 0
right = len(nums) - 1
i = 0
while i <= right:
if nums[i] == 0:
nums[left], nums[i] = nums[i], nums[left]
left += 1
i += 1
# 交换后这里是left值正常是0
elif nums[i] == 2:
nums[right], nums[i] = nums[i], nums[right]
right -= 1
# 交换后这里为right值需要检查
else:
i += 1