题目:
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
- 一个直观的解决方案是使用计数排序的两趟扫描算法。首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
- 你能想出一个仅使用常数空间的一趟扫描算法吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-colors
方法一:
双指针:一个指针指向白色的第一个、一个指针指向蓝色的第一个。
遍历数组:
- 如果当前遍历的颜色是红色,则当前位置先与白色第一个交换,交换完毕后,当前位置再于蓝色第一个交换;
- 如果当前遍历的颜色是白色,则与蓝色第一个交换;
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
white_index = 0
blue_index = 0
l = len(nums)
if l<=1:
return
for i in range(l):
if nums[i] == 0:
c = nums[i]
nums[i] = nums[white_index]
nums[white_index] = c
white_index += 1
blue_index = max(white_index, blue_index)
if nums[i] == 1:
c = nums[i]
nums[i] = nums[blue_index]
nums[blue_index] = c
blue_index += 1