c# - 三个给定数组的前 5 个值

标签 c# algorithm sorting

最近遇到一个问题 C#,问题是:- 一共有三个int数组

Array1={88,65,09,888,87}

Array2={1,49,921,13,33}

Array2={22,44,66,88,110}

现在我必须从所有这三个数组中获取最高 5 的数组。在 C# 中执行此操作的最优化方法是什么?

我能想到的方法是取一个大小为 15 的数组,然后添加所有三个数组的数组元素,然后对其进行排序,得到最后 5 个。

最佳答案

使用 LINQ 的简单方法:

int[] top5 = array1.Concat(array2).Concat(array3).OrderByDescending(i => i).Take(5).ToArray();

最佳方式:

 List<int> highests = new List<int>(); // Keep the current top 5 sorted
 // Traverse each array. No need to put them together in an int[][]..it's just for simplicity
 foreach (int[] array in new int[][] { array1, array2, array3 }) {
     foreach (int i in array) {
         int index = highests.BinarySearch(i); // where should i be?

         if (highests.Count < 5) { // if not 5 yet, add anyway
             if (index < 0) {
                highests.Insert(~index, i);
             } else { //add (duplicate)
                highests.Insert(index, i);
             }
         }
         else if (index < 0) { // not in top-5 yet, add
             highests.Insert(~index, i);
             highests.RemoveAt(0);
         } else if (index > 0) { // already in top-5, add (duplicate)
             highests.Insert(index, i);
             highests.RemoveAt(0);
         }
     }
 }

保留前 5 名的排序列表并遍历每个数组仅一次

您甚至可以每次检查前 5 名中最低的,避免二元搜索:

 List<int> highests = new List<int>();
 foreach (int[] array in new int[][] { array1, array2, array3 }) {
     foreach (int i in array) {
         int index = highests.BinarySearch(i);
         if (highests.Count < 5) { // if not 5 yet, add anyway
             if (index < 0) {                    
                highests.Insert(~index, i);
             } else { //add (duplicate)
                highests.Insert(index, i);
             }
         } else if (highests.First() < i) { // if larger than lowest top-5                
             if (index < 0) { // not in top-5 yet, add
                highests.Insert(~index, i);
                highests.RemoveAt(0);
             } else { // already in top-5, add (duplicate)
                highests.Insert(index, i);
                highests.RemoveAt(0);
             }
         }
     }
}

关于c# - 三个给定数组的前 5 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594634/

相关文章:

c# - DropdownList 选择要标记的值

C# 等效于 Delphi 的 .INI 读取方法

algorithm - 如何在合并排序中控制我的算法的堆栈溢出

algorithm - 修改 Euler Totient 函数

java - Hadoop MapReduce 使用键对归约输出进行排序

javascript - Angular 日期排序自定义函数

c# - Windows Phone 8 上的特殊字符与 StreamReader

c# - MVC : View and Model Interaction Regarding Data Access, 等

string - 如何编写一个接受字符串并返回最长有效子字符串的方法

c - 直接插入排序的错误 C 实现