Problem
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
Because the last element of the row is the biggest number of that row, if the target element is greater than that last number, the target element cannot be on the current row and the rows above the current row.
-
We can use binary search method to find out the target row that the target element is in, then we use binary search method again to find out if the target element is in the target row.
Solution
1 |
|