猿问

C#按顺序分区排序数字

我的数据如下:

5 2 2 1 3 3 4

我想在 C# 中输出如下:

1 2 3 4 5 2 3

所以基本上所有的唯一值首先按 ASC 顺序排序,而不是从剩余的项目开始......


慕慕森
浏览 182回答 2
2回答

MMTTMM

您可以按值对数据进行分组,对组进行排序,然后在记住计数的情况下迭代组 - 每次递减并在达到零时删除事物,或者增加计数器并仅输出至少人口众多的事物。就像是:var values = new[] { 5, 2, 2, 1, 3, 3, 4 };var data = new SortedDictionary<int, int>();foreach(var val in values){&nbsp; &nbsp; int count;&nbsp; &nbsp; if (!data.TryGetValue(val, out count)) count = 0;&nbsp; &nbsp; data[val] = count + 1;}int lim = 0;bool any;do{&nbsp; &nbsp; any = false;&nbsp; &nbsp; foreach (var pair in data)&nbsp; &nbsp; &nbsp; &nbsp; if (pair.Value > lim)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(pair.Key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; any = true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; lim++;} while (any);
随时随地看视频慕课网APP
我要回答