[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.

click to show follow up.

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?

 
Solution 1:
 1 public class Solution {
 2     public void sortColors(int[] A) {
 3       if(A.length<=1)
 4             return;
 5         int iRed=0,iBlue=A.length-1;
 6         int i=0;
 7         while(i<=iBlue){
 8             if(A[i]==0){
 9                 int temp=A[iRed];
10                 A[iRed]=A[i];
11                 A[i]=temp;
12                 iRed++;
13                 i++;   //cannot be less than iRed 
14             }else if(A[i]==2){
15                 int temp=A[iBlue];
16                 A[iBlue]=A[i];
17                 A[i]=temp;
18                 iBlue--;
19             }else{
20                 i++;
21             }
22         }
23 }
24 }

Solution 2:

 1 public class Solution {
 2     public void sortColors(int[] A) {
 3         int i=-1;   //pointer for 0s
 4         int j=-1;   //pointer for 1s
 5         int k=-1;   //pointer for 2s
 6         for(int m=0;m<A.length;++m){
 7             if(A[m]==0){
 8                 A[++k]=2;
 9                 A[++j]=1;
10                 A[++i]=0;
11             }else if(A[m]==1){
12                 A[++k]=2;
13                 A[++j]=1;
14             }else{
15                 A[++k]=2;
16             }
17         }
18     }
19 }

 i,j,k三个指针分别指向0,1,2段的结尾处。

posted @ 2014-11-12 16:05  Phoebe815  阅读(156)  评论(0编辑  收藏  举报