Ricochet: Ricochet
Given an array nums of n elements red, white, and blue, sort them in-place so that elements of the same color are next to each other in the order red, white, and blue.
We use the integers 0, 1, and 2 to represent red, white, and blue, respectively.
This problem must be solved without using the library's built-in 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]
hint:
n == nums.length
1 <= n <= 300
nums[i] 为 0、1 或 2
Sample code 1: [Three pointers]
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]
size = len(nums)
zero = 0
two = size
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)