Binary Search Searching a matrix
257. Find a Peak Element II
You are given a grid of integers mat with m rows and n columns. Return the position of any peak in
it as [row, col]. Rows and columns are counted from 0.
A cell is a peak when it is larger than each of its neighbours: the cells directly above, below, left and right of it. Diagonal cells are not neighbours. Every position outside the grid counts as −∞, so a cell on the edge only has to be larger than the neighbours it has.
A grid can have several peaks, and any of them is a correct answer. The result shows a peak when the cell
you return is one. Otherwise it says what is wrong, such as [1,2] is not a peak or [0,5] is outside the grid.
Aim for O(m log n) or O(n log m) time.
Example 1
Input: mat = [[4, 9, 3, 8], [6, 2, 7, 5], [1, 11, 10, 12]]
[1,0]Explanation: 6 is larger than 4 above it, 1 below it and 2 on its right, and the left side is outside the grid. The cells holding 9, 8, 11 and 12 are peaks too, and any of the five is correct.
Example 2
Input: mat = [[-7], [-3], [-12], [-5]]
[1,0]Explanation: Every value is negative. −3 is larger than −7 above it and −12 below it. −5 at the bottom is a peak too: it is larger than −12, and the position below it is outside the grid.
Example 3
Input: mat = [[-1000000000]]
[0,0]Explanation: A grid of one cell has no neighbours, so that cell is a peak, even though it holds the smallest value allowed.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == mat.length,n == mat[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 105-109 ≤ mat[i][j] ≤ 109- No two neighbouring cells hold equal values.
Clarifying questions
What you would ask an interviewer before writing any code.