每日一题 2019 - 04 - 10
题目:
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:
1 | Input: [2,0,2,1,1,0] |
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
,要求是每个数字都聚在一起,就像 example
给出的例子,直观的解题思路,一个sort
函数就可以解决问题,但是这个题让我们尝试使用使用一趟遍历就解决问题,所以就引进了一个新的算法,也即Dutch national flag problem ;
这个算法的思路简单可解释如下:
- 设置三指针
i
、j
、n
,i
代表最小元素往后递推的当前所处位置j
代表当前遍历的位置n
代表最大元素当前往前递推所处的位置
- 设置
mid
为待排三元素的中间值 - 随后开始遍历:
1 | while(j <= n) |
代码:
1 | class Solution { |