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.
Note:
You are not suppose to use the library’s sort function for this problem.
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 an one-pass algorithm using only constant space?
解法1: Bucket sort/counting sort, O(N) Time with two passes
Bucket sort, 统计0,1,2的个数然后再逐个写入
C++
Java
解法2: One pass O(N)
类似于双指针的思路,这里用了一个low记录0的位置,用了一个high记录2的位置,然后从左往右扫描. 如果是0或者2就知道该插入在什么地方,如果是1那么就往前移动.
C++
###解法3: One pass O(N) ###
用两个指针记录zero和one插入的位置。
对于每一个新数字,先插入最大的数字。因为如果是其他数字的话在之后的操作中会被覆盖。
然后从大到小的判断当前数字为哪一个。如果是1那么只移动one的位置并插入。
如果是zero,那么需要先移动one并且赋值,然后移动zero再赋值。如果zero插入的位置原本是一个1,那么被覆盖的1就被one的指针找回了。
Java