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.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
解法1:
这题有两种做法,都用到了binary search。一种只需要一次binary search,也就是下面的这种解法。但缺点是row×col可能会溢出,同时取余数的操作比较expensive。
还有一种是两次binary search。先用一次找出最后一行其中第一个数字小于target,然后再这行再用一次binary search。
C++
Java