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.
Key to solve: 3 pointers
Since there are 3 distinguish type of colors
we can set up 3 additional pointers start from 0
Assign value by increasing order since we are going to sort array by increasing order
There are 3 cases:
0: assign all 3 colors
1: assign two colors
2: assign only one color
public class Solution {
public void sortColors(int[] A) {
if(A.length==0) return;
int red=0, white=0,blue=0;
for(int i=0;i<A.length;i++){
if(A[i]==0){
A[blue++]=2;
A[white++]=1;
A[red++]=0;
}else if(A[i]==1){
A[blue++]=2;
A[white++]=1;
}else{
A[blue++]=2;
}
}
}
}