```
// The basic idea is to keep four divisions for 0s, 1s, 2s and unselected elments in the array respectively .
// when the element is 2, just increse the index index2 and insert the element.
//when the element is 1, check conditions. to insert 1 and 2 or sth else.
// when it is 0, it becomes a little bit complicated.. since you need to consider all the cases.
public class Solution {
public void sortColors(int[] nums) {
int index0, index1, index2;
index0 = index1 = index2 = - 1;
int len = nums.length;
for(int i = 0 ; i < len; i++){
if(nums[i] == 0){
index0 = index0 + 1;
index1 = index1 + 1;
index2 = index2 + 1;
nums[index0] = 0;
if(index2 > index1 && index1 == index0){
// has 2 no 1
nums[index2] = 2;
}else if(index1 == index2 && index1 != index0){
//has 1 no 2
nums[index1] = 1;
}else if(index1 == index2 &&index1 == index0){
}else{
//has both
nums[index1] = 1;
nums[index2] = 2;
}
}else if(nums[i] == 1){
index1 = index1 + 1;
index2 = index2 + 1;
nums[index1] = 1;
if(index1 != index2){
nums[index2] = 2;
}
}else{
index2 = index2 + 1;
nums[index2] = 2;
}
}
}
}
```