[LeetCode-75] Sort Colors

Sort Colors

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 class Solution {
 2     public:
 3         void sortColors(int A[], int n) {
 4             // Start typing your C/C++ solution below
 5             // DO NOT write int main() function
 6             int cnt_r = 0, cnt_w = 0, cnt_b = 0, index = 0;
 7             for (int i = 0; i < n; ++i) {
 8                 switch (A[i]) {
 9                     case 0:
10                         ++cnt_r;
11                         break;
12                     case 1:
13                         ++cnt_w;
14                         break;
15                     case 2:
16                         ++cnt_b;
17                         break;
18                     default:
19                         break;
20                 }
21             }
22             while (cnt_r--) {
23                 A[index++] = 0;
24             }
25             while (cnt_w--) {
26                 A[index++] = 1;
27             }
28             while (cnt_b--) {
29                 A[index++] = 2;
30             }
31         }
View Code

 

posted on 2013-08-19 11:23  似溦若岚  阅读(145)  评论(0编辑  收藏  举报

导航