Binary Search Searching a matrix
258. Median of a Row Wise Sorted Matrix
You are given a grid of integers grid with m rows and n columns. Every row is sorted in non-decreasing
order, and the number of cells, m · n, is odd. Return the median of all the values in the grid.
The median is the middle value once all m · n values are written out in sorted order. Equal values
each take their own place in that order, so a value that appears three times takes three places.
Only the rows are sorted. The grid as a whole need not be: a row can start below the end of the row above it. Try to find the median in less than O(m · n) time.
Example 1
Input: grid = [[2, 5, 11], [1, 3, 8], [4, 6, 6]]
5Explanation: In sorted order the nine values are 1, 2, 3, 4, 5, 6, 6, 8, 11. The fifth of them, 5, is in the middle.
Example 2
Input: grid = [[-4, 0, 7, 7, 9],
[-9, -4, -4, 2, 3],
[1, 1, 1, 1, 1]]
1Explanation: Five values are smaller than 1 and five are larger. The middle value, the eighth of 15, is one of the five 1s.
Example 3
Input: grid = [[-1000000000], [1000000000], [0]]
0Explanation: Each row holds one value, so every row is sorted. In order the values are -1000000000, 0 and 1000000000.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == grid.length,n == grid[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 105, andm · nis odd.-109 ≤ grid[i][j] ≤ 109- Each row of
gridis sorted in non-decreasing order.
Clarifying questions
What you would ask an interviewer before writing any code.