c# - 对 0、1 和 2 的数组进行排序(进一步优化)
问题描述
下面是一个非常简单的代码,它对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;
}
解决方案
这是计数排序的示例。虽然据我所知无法降低渐近复杂度,但您可以专注于减少常数。例如不需要构造字典,数组就可以了。如果我们保证我们只会看到 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++;
}
推荐阅读
- swagger - swagger-editor vs swagger-codegen
- android - 可以更新在 Google Play 商店外安装的应用程序吗?
- amazon-web-services - AWS S3 慢速下载
- visual-studio-code - vsCode 和 cssComb
- java - 如何遍历十进制搜索树?(Java)(最多有 10 个孩子而不是 2 个)
- .net - 将 .Net 标准 2.0 库与 UWP 应用程序一起使用时出现 HttpClient 异常
- startup - 启动后一分钟无法打开chrome
- excel - 查找 table_array 参数增量
- mysql - 直接同步来自不同供应商的两个数据库?(甲骨文和 MySQL)
- sql - 如何仅使用子查询编写此 Oracle SQL 查询