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). 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).
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
We find the rank of this element in O(m log n)
. ie: in each row how many elements are lower than the pivot found in step (1).
By comparing k
and "rank of the pivot" we can know that in each row works on the right half or left half. (reduce to m*n/2
matrix.)
But the time complexity of this algorithm is O(m * log^2 n)
. What is the algorithm that can works on O(m (log n + log m))
? Is there any idea?
m - rows n - columns
Is it compulsory that you want a solution with O(m (log m+ log n))
Complexity?
I Can Think of a Solution with Complexity O(k * log-m)
with extra space of 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
Ultimately the problem comes down to find the kth smallest element in M sorted arrays.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.