public void sortColors(int[] A) {
if(A==null || A.length==0)
return;
int[] res = new int[A.length];
int[] helper = new int[3];
for(int i=0;i<A.length;i++)
{
helper[A[i]]++;
}
for(int i=1;i<3;i++)
{
helper[i]=helper[i]+helper[i-1];
}
for(int i=A.length-1;i>=0;i--)
{
res[helper[A[i]]-1] = A[i];
helper[A[i]]--;
}
for(int i=0;i<A.length;i++)
{
A[i] = res[i];
}
}上面的代码是计数排序的标准解法。能够看到总共进行了三次扫描,事实上最后一次仅仅是把结果数组拷贝到原数组而已。假设不须要in-place的结果仅仅须要两次扫描。public void sortColors(int[] A) {
if(A==null || A.length==0)
return;
int idx0 = 0;
int idx1 = 0;
for(int i=0;i<A.length;i++)
{
if(A[i]==0)
{
A[i] = 2;
A[idx1++] = 1;
A[idx0++] = 0;
}
else if(A[i]==1)
{
A[i] = 2;
A[idx1++] = 1;
}
}
}上述方法时间复杂度还是O(n)。仅仅是仅仅须要一次扫描,空间上是O(1)(假设颜色种类是已知的话)。原文:http://www.cnblogs.com/yxwkf/p/5164321.html