Leetcode.75 Sort Colors
Given an array 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.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
- A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. - Could you come up with a one-pass algorithm using only constant space?
Solution
题目相当于0、1、2排序,而且是有重复数据的排序
解法一:计数排序
class Solution:
def sort_colors_violent(self, nums: list) -> None:
pass
def sort_colors_count_sort(self, nums: list) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 定义一个存储空间,存储0,1,2的频次
count = [0, 0, 0]
n = len(nums)
for i in range(n):
count[nums[i]] += 1
index = 0
while count[0] > 0:
nums[index] = 0
index += 1
count[0] -= 1
while count[1] > 0:
nums[index] = 1
index += 1
count[1] -= 1
while count[2] > 0:
nums[index] = 2
index += 1
count[2] -= 1
复杂度:
- 时间复杂度:O(n+n)
- 空间复杂度:O(k)
解法二:三路快排
由于是有重复的排序,并且只有三个数字,因此可以考虑三路快排序的partition思想
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# [0,zero] -> 0
# [zero+1,i] -> 1
# [two,n-1] -> 2
n = len(nums)
zero = -1
two = n
i = 0
# 注意循环结束条件,到two即可,由于two后边已经排列好
while i < two:
if nums[i] == 0:
zero += 1
nums[i],nums[zero] = nums[zero],nums[i]
i += 1
elif nums[i] == 1:
i += 1
else:
assert nums[i] == 2
two -= 1
nums[i],nums[two] = nums[two],nums[i]