Sort Color
题目描述
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
解题方法
quick select 模板解决
Solution
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
def swap(p1, p2):
tmp = nums[p2]
nums[p2] = nums[p1]
nums[p1] = tmp
length = len(nums)
if length == 0:
return
left = 0
right = length - 1
p = 0
while p <= right:
if nums[p] < 1:
swap(left, p)
p += 1
left += 1
elif nums[p] == 1:
p += 1
else:
swap(right, p)
right -= 1