Leetcode 75 Sort Colors.

Problem 75 Sort Colors

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.

Not a hard one, but I spend a lot of time on it. Because of a very small mistake.

The idea of this problem is sort, and you can find the variety of this problem is really small, so the best sort way is counting sort. Then the rest things are not so hard. And we do not have any labels for this, so no need to build a new array.

PS: The mistake I made was res=res+c[j]; I place it in the circulation.

public class Solution {
public void sortColors(int[] nums) {
int length=nums.length;
if(nums.length < 2){
return;
}
int[] c=new int[3];
c[0]=0;
c[1]=0;
c[2]=0;
for(int i=0;i < nums.length;i++){
c[nums[i]]=c[nums[i]]+1;
}

int i=0;
int j=0;
int res=0;
for(j=0;j <= 2;j++){
for(i=0;i < c[j];i++){
if(i+res < length){
nums[i+res]=j;
}else{
return;
}
}res=res+c[j];
}

}
}