Description
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
You must find a solution with a memory complexity better than O(n2).
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Example 2:
Input: matrix = [[-5]], k = 1
Output: -5
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 300109 <= matrix[i][j] <= 109- All the rows and columns of
matrixare guaranteed to be sorted in non-decreasing order. 1 <= k <= n2
Solutions
Solution 1
Intuition
- binary search this number
- search how many numbers are smaller than the mid, and count them as
cnt - if
cnt≥ k, means thekthsmallest number is in left part, sor = mid, else search the right part
Code
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix.size();
int l = matrix[0][0], r = matrix[n - 1][n - 1], mid;
while (l < r) {
int mid = l + r >> 1;
int col = n - 1, cnt = 0;
for (int row = 0; row < n; row++) {
while (col >= 0 && matrix[row][col] > mid) col--;
cnt += col + 1;
}
if (cnt >= k)
r = mid;
else
l = mid + 1;
}
return l;
}
};
Complexity
- Time: O(n)
- Space: O(1)
Top comments (0)