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?

解题思路

基本按照计数排序的思路,先遍历统计0、1、2的个数。根据个数重新对数组赋值。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count = [0, 0, 0]
for i in nums:
count[i] += 1
print(count)
print(nums[:count[i]])
nums[:count[0]] = [0]*count[0]
nums[count[0]:count[1]+count[0]] = [1]*count[1]
nums[count[1]+count[0]:] = [2]*count[2]

进阶思路

上述做法貌似需要 \(O(n)\) 的额外存储空间,如果 \(O(1)\) 来做又会导致遍历两次。因此可以考虑类似快速排序的做法,两个指针分别指向头尾,一个指针从左到右移动。。将遇到的2移动到最右边,遇到的0移动到最左边。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def sortColors(self, nums: 'List[int]') -> 'None':
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums)<=1:
return

l = 0
r = len(nums) - 1
i=0
while i<=r:
if nums[i] == 2 and i<r:
nums[i], nums[r] = nums[r], nums[i]
r-=1
elif nums[i] == 0 and i>l:
nums[i], nums[l] = nums[l], nums[i]
l+=1
else:
i+=1
return