Saturday, January 5, 2013

[LeetCode] 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.
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?
» Solve this problem

[解题思路]

i从0到blue index扫描，

[Code]
two-pass solution, Counting sort solution
``````1:       void sortColors(int A[], int n) {
2:            // Start typing your C/C++ solution below
3:            // DO NOT write int main() function
4:            int red=0, white =0, blue=0;
5:            for(int i =0; i < n; i++)
6:            {
7:                 switch(A[i])
8:                 {
9:                 case 0:
10:                      red++;break;
11:                 case 1:
12:                      white++;break;
13:                 case 2:
14:                      blue++;break;
15:                 }
16:            }
17:            for(int i =0; i<n; i++)
18:            {
19:                 if(red>0)
20:                 {
21:                      A[i]=0;
22:                      red--;
23:                      continue;
24:                 }
25:                 if(white>0)
26:                 {
27:                      A[i] =1;
28:                      white--;
29:                      continue;
30:                 }
31:                 A[i]=2;
32:            }
33:       }
``````

one-pass, two pointers solution
``````1:       void sortColors(int A[], int n) {
2:            // Start typing your C/C++ solution below
3:            // DO NOT write int main() function
4:            int redSt=0, bluSt=n-1;
5:            int i=0;
6:            while(i<bluSt+1)
7:            {
8:                 if(A[i]==0)
9:                 {
10:                      std::swap(A[i],A[redSt]);
11:                      redSt++;
12:                      i++;
13:                      continue;
14:                 }
15:                 if(A[i] ==2)
16:                 {
17:                      std::swap(A[i],A[bluSt]);
18:                      bluSt--;
19:                      continue;
20:                 }
21:                 i++;
22:            }
23:       }
``````