378. Kth Smallest Element in a Sorted Matrix
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
Note: You may assume k is always valid, 1 ≤ k ≤ n^2.
Thoughts:
Heap:
Build a minHeap of elements from the first row.
Repeat for k - 1 times: poll out the current element from the queue, get its row and col number. if row is not at the end (n-1), push a new element at the same column, next row into the queue
return the kth smallest value by pop out of the queue
Binary Search: 1. binary search the value in matrix to get its rank on the matrix:
if rank < k: low = mid + 1
hi = mid
return lo(or hi) in the end
Code: Heap T: O(k*logn); S: O(n)
Code: Binary Search: T:O(n*log(max - min));S: O(1)
Last updated
Was this helpful?