C#:在 N x N 矩阵中查找最大 m 个元素的高效算法

标签 c# algorithm matrix

我想知道是否有一种有效的算法来查找 N x N 矩阵中最大的 m 个元素,其方法头如下所示:

double[] greatestValues(double[][] matrix, int numberOfElements);

有什么想法吗?

最佳答案

如果将 N x N 矩阵视为 N x N 项的数组,则可以应用以下技术之一:

Direct application of the quick sort based selection algorithm The quick sort based selection algorithm can be used to find k smallest or k largest elements. To find k smallest elements find the kth smallest element using the median of medians quick sort based algorithm. After the partition that finds the kth smallest element, all the elements smaller than the kth smaller element will be present left to the kth element and all element larger will be present right to the kth smallest element. Thus all elements from 1st to kth element inclusive constitute the k smallest elements. The time complexity is linear in n, the total number of elements.

Data structure based solutions Another simple method is to add each element of the list into an ordered set data structure, such as a heap or self-balancing binary search tree, with at most k elements. Whenever the data structure has more than k elements, we remove the largest element, which can be done in O(log k) time. Each insertion operation also takes O(log k) time, resulting in O(nlog k) time overall.

It is possible to transform the list into a heap in Θ(n) time, and then traverse the heap using a modified Breadth-first search algorithm that places the elements in a Priority Queue (instead of the ordinary queue that is normally used in a BFS), and terminate the scan after traversing exactly k elements. As the queue size remains O(k) throughout the traversal, it would require O(klog k) time to complete, leading to a time bound of O(n + klog k) on this algorithm.

来自here .

关于C#:在 N x N 矩阵中查找最大 m 个元素的高效算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/814186/

相关文章:

algorithm - 只需一次操作即可获得位串中第一个有效位的位置

algorithm - 给定一个数字系列,找到校验位算法......?

c# - 异步等待调用不返回

在图中查找前 K 路径的算法,没有公共(public)顶点,负权重?

c# - 用于基于约定的 ASP.NET MVC 开发的软件堆栈

r - 在 R 中传递大型矩阵的替代方法

python - 使 numpy.sum() 返回矩阵总和而不是单个数字

c++ - 用于矩阵加法的 Cuda 程序

C# - 如何在不使用 BindingSource 的情况下在 DataGridView 中搜索和筛选

c# - 在 C# 中按类名作为字符串获取类属性