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?
Difficulty: naive practice 60, counting and sorting
1 public class Solution { 2 public void sortColors(int[] A) { 3 if (A == null || A.length == 0) return; 4 int[] colornum = new int[3]; 5 for (int elem : A) { 6 if (elem == 0) colornum[0]++; 7 if (elem == 1) colornum[1]++; 8 if (elem == 2) colornum[2]++; 9 }10 for (int i=0; i<colornum[0]; i++) {11 A[i] = 0;12 }13 for (int i=colornum[0]; i<colornum[0]+colornum[1]; i++) {14 A[i] = 1;15 }16 for (int i=colornum[0]+colornum[1]; i<A.length; i++) {17 A[i] = 2;18 }19 }20 }
We will consider how to use a single scan.
There is a practice on the Internet that I have not understood yet.
1 public void sortColors(int[] A) { 2 if(A==null || A.length==0) 3 return; 4 int idx0 = 0; 5 int idx1 = 0; 6 for(int i=0;i<A.length;i++) 7 { 8 if(A[i]==0) 9 {10 A[i] = 2;11 A[idx1++] = 1;12 A[idx0++] = 0;13 }14 else if(A[i]==1)15 {16 A[i] = 2;17 A[idx1++] = 1;18 }19 }20 }
Leetcode: Sort colors