题目描述
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
题解
计数排序
from collections import Counter
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# temp = sorted(nums)
# for i,j in enumerate(temp):
# nums[i] = j
temp = Counter(nums)
temp = [0]*temp[0]+[1]*temp[1]+[2]*temp[2]
for i,j in enumerate(temp):
nums[i] = j
也可以使用三路快排