# 75.sort-colors

## Statement

• Difficulty: Medium
• Tag: 数组 双指针 排序

• n == nums.length
• 1 <= n <= 300
• nums[i]012

• 你可以不使用代码库中的排序函数来解决这道题吗？
• 你能想出一个仅使用常数空间的一趟扫描算法吗？

• Difficulty: Medium
• Tag: Array Two Pointers Sorting

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]

Constraints:

• n == nums.length
• 1 <= n <= 300
• nums[i] is either 0, 1, or 2.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

## Solution

from typing import List

class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
l, r = 0, n - 1
for i in range(n):
pre = nums[i]
while True:
if nums[i] == 0:
while l < i and nums[l] == 0:
l += 1
nums[l], nums[i] = nums[i], nums[l]
elif nums[i] == 2:
while r > i and nums[r] == 2:
r -= 1
nums[r], nums[i] = nums[i], nums[r]
else:
break

if nums[i] == pre:
break

pre = nums[i]