Given an array with n objects colored red, white or blue, sort them so, objects of the same color is Adjacen T, with the colors in the order red, white and blue.
Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You is not a 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 a one-pass algorithm using only constant space?
A simple counting sequence that requires two traversal.
Public classSolution { Public voidSortcolors (int[] nums) { intCount0=0; intCount1=0; intCount2=0; intL=nums.length; for(inti=0;i<l;i++){ if(nums[i]==0) count0++; Else if(nums[i]==1) {Count1++; }Else if(nums[i]==2) {Count2++; } } for(intj=0;j<l;j++){ if(j<count0) {Nums[j]=0; }Else if(j<count0+count1) {Nums[j]=1; }Else{Nums[j]=2; } } }}
View Code
One traversal algorithm: Transfer from http://blog.csdn.net/yangliuy/article/details/40584683
Public classSolution { Public voidSortcolors (int[] A) {//Implement Counting Sort intCount1 = 0; intCount2 = 0; intcount0 = 0; for(inti = 0; i < a.length; i++){ if(A[i] = = 2) {Count2++; } Else if(A[i] = = 1) {Count1++; Swap (A, I, I-Count2); } Else{count0++; Swap (A, I, I-Count2); Swap (A, I-count2, i-count2-count1); } } } Public voidSwapint[] A,intIintj) { inttemp; Temp=A[i]; A[i]=A[j]; A[J]=temp; }}
View Code
Leetcode 75Sort Colors