下面是一个非常简单的代码,它对 0s,1s和2s 进行排序 数组。我相信时间复杂度是 O(N),对吗?如何进一步改进以将时间复杂度降低到 O(logN)左右?
//Input: 0 2 1 2 0
//Output: 0 0 1 2 2
public static int[] SortArray012(int[] array)
{
Dictionary<int, int> result = new Dictionary<int, int>(3);
int[] sortedResult = new int[array.Length];
int i = 0;
foreach(int no in array)
{
if (result.ContainsKey(no))
result[no]++;
else
result.Add(no, 1);
}
for (; i < result[0]; i++)
sortedResult[i] = 0;
for (; i < result[0] + result[1]; i++)
sortedResult[i] = 1;
for (; i < result[0] + result[1] + result[2]; i++)
sortedResult[i] = 2;
return sortedResult;
}
答案 0 :(得分:4)
这是计数排序的示例。虽然据我所知,没有办法降低渐近复杂度,但您可以集中精力减少常数。例如,无需构造字典,数组即可。如果我们保证只看到1,2和0,则不需要if语句。我们还可以使用两个for循环而不是三个
来生成结果int[] test = {1,1,0,2,1,0};
int[] count = {0,0,0};
int[] result = new int[test.Length];
foreach(int no in test){
count[no]++;
}
int i = 0;
int k = 0;
foreach(int c in count){
for(int j = 0; j < c; j++){
result[k++] = i;
}
i++;
}