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 if(n == 0) 5 return; 6 int zero = 0,two = n-1; 7 for(int i = 0;i <= two;){ 8 if(A[i] == 0){ 9 swap(A[i],A[zero]); 10 zero++; 11 i++; 12 } 13 else if(A[i] == 1) 14 i++; 15 else if(A[i] == 2){ 16 swap(A[i],A[two]); 17 two--; 18 } 19 } 20 } 21 };
JAVA版本代码:
1 public class Solution { 2 int[] swap(int[] A,int i,int j){ 3 int temp = A[i]; 4 A[i] = A[j]; 5 A[j] = temp; 6 return A; 7 } 8 public void sortColors(int[] A) { 9 if(A.length == 0) 10 return; 11 int zero = 0; 12 int two = A.length - 1; 13 for(int i = 0;i <= two;){ 14 if(A[i] == 2){ 15 swap(A, i, two); 16 two--; 17 } 18 19 else if(A[i] == 1) 20 i++; 21 22 else if(A[i] == 0) 23 { 24 swap(A, i, zero); 25 zero++; 26 i++; 27 } 28 } 29 } 30 }