matrix is an n × n grid in which every row is sorted from smallest to largest, left to right, and every column is sorted from smallest to largest, top to bottom. Return the k-th smallest value in the whole grid.
The count is over cells, not over distinct values: a value that appears in three cells takes three places in the order.
Aim for less than O(n²) extra memory.
In order, the nine values are 1, 3, 4, 5, 6, 7, 8, 9, 12. The 5th is 6.
The two -2s are the 1st and 2nd smallest values.
Constraints
n == matrix.length == matrix[i].length1 <= n <= 300-10⁹ <= matrix[i][j] <= 10⁹1 <= k <= n²The smallest value is in the top-left corner. Once a cell has been counted, the next candidates are only the cell to its right and the cell below it, so you never need to sort the whole grid.
6