[英]Algorithm with O(m (log n + log m)) time complexity for finding kth smallest element in n*m matrix with each row sorted?
I ran into an interview question recently.我最近遇到了一个面试问题。
We have
m*n
matrix such that each row is in non-decreasing order (sorted with distinct elements).我们有
m*n
矩阵,使得每一行都按非递减顺序(用不同的元素排序)。 design an algorithm on orderO(m (log m+ log n))
to findk
-th smallest element on this matrix (just one element ask
-th smallest element).设计一个
O(m (log m+ log n))
阶的算法来找到这个矩阵上的第k
个最小元素(只有一个元素作为第k
个最小元素)。
I think this is not possible so search on Google and find this link and another solution and this answer to a similar question .我认为这是不可能的,所以在谷歌上搜索并找到这个链接和另一个解决方案以及这个类似问题的答案。
I think as follows:我认为如下:
Put the median of all rows into an array and we find the median of this array in O(m)
and called it pivot将所有行的中值放入一个数组中,我们在
O(m)
中找到该数组的中值,并将其命名为 pivot
We find the rank of this element in O(m log n)
.我们在
O(m log n)
中找到该元素的等级。 ie: in each row how many elements are lower than the pivot found in step (1).即:在每一行中有多少元素低于步骤(1)中找到的 pivot。
By comparing k
and "rank of the pivot" we can know that in each row works on the right half or left half.通过比较
k
和“枢轴的等级”,我们可以知道每一行都在右半边或左半边工作。 (reduce to m*n/2
matrix.) (减少到
m*n/2
矩阵。)
But the time complexity of this algorithm is O(m * log^2 n)
.但是这个算法的时间复杂度是
O(m * log^2 n)
。 What is the algorithm that can works on O(m (log n + log m))
?可以在
O(m (log n + log m))
上运行的算法是什么? Is there any idea?有什么想法吗?
m - rows n - columns m - 行 n - 列
Is it compulsory that you want a solution with O(m (log m+ log n))
Complexity?您是否需要具有
O(m (log m+ log n))
复杂度的解决方案?
I Can Think of a Solution with Complexity O(k * log-m)
with extra space of O(m)我可以想出一个复杂度为
O(k * log-m)
且额外空间为 O(m) 的解决方案
class PQObject { int value; // PQ sorting happens on this int.. int m; // And m and n are positions. int n; }
You can just put all the values from the first column to the Priority Queue and Start popping until the kth smallest element您可以将第一列中的所有值放入优先级队列并开始弹出直到第 k 个最小元素
Ultimately the problem comes down to find the kth smallest element in M sorted arrays.最终问题归结为在 M 排序的 arrays 中找到第 k 个最小的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.