Leetcode OJ: Sort Color

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?

第一反应就是排序,但题目不能用,然后就是hash,也不能用。接着就想到类似选择排序的思路了。

i, k表示开头与结尾的下标,然后j为当前扫描点的下标,判断为0则放i中,i++,判断为2则放k中,k++,其它j++。

由于LZ比较心急,写的时候以为当前扫描点与交换的点是可以一起换,所以写成了swap(A[i++], A[j++])类似这样的形式,然后就果断出错了。

这里需要注意的是,每扫描一次,只改变一个下标(i 或 j 或 k),不要太贪心了!

代码如下:

 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) {
 4         int i = 0, k = n - 1;
 5         int j = i;
 6         while (j <= k) {
 7             if (A[j] == 0) {
 8                 if (j > i)
 9                     swap(A[i++], A[j]);
10                 else {
11                     ++i;
12                     ++j;
13                 }
14             } else if (A[j] == 2) {
15                 if (j < k) {
16                     swap(A[j], A[k--]);
17                 } else {
18                     break;
19                 }
20             } else
21                 ++j;
22         }
23     }
24 };

 

 
posted @ 2014-04-04 11:24  flowerkzj  阅读(178)  评论(0编辑  收藏  举报