问题描述
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 | class Solution: |
进阶思路
上述做法貌似需要 \(O(n)\) 的额外存储空间,如果 \(O(1)\) 来做又会导致遍历两次。因此可以考虑类似快速排序的做法,两个指针分别指向头尾,一个指针从左到右移动。。将遇到的2移动到最右边,遇到的0移动到最左边。
1 | class Solution: |