74. The two-dimensional matrix search
Prepared by an efficient algorithm to determine the mxn matrix, the presence or absence of a target value. This matrix has the following characteristics:
An integer of from left to right in each row in ascending order.
The first integer is greater than the last row of each integer previous row.
Example 1:
Input:
Matrix = [
[. 1,. 3,. 5,. 7],
[10,. 11, 16, 20 is],
[23 is, 30, 34 is, 50]
]
target =. 3
Output: true
Example 2:
Input:
Matrix = [
[. 1,. 3,. 5,. 7],
[10,. 11, 16, 20 is],
[23 is, 30, 34 is, 50]
]
target = 13 is
output: false
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0)
return false;
int begin, mid, end;
begin = mid = 0;
int len1 = matrix.length, len2 = matrix[0].length;
end = len1 * len2 - 1;
while (begin < end) {
mid = (begin + end) / 2;
if (matrix[mid / len2][mid % len2] < target)
begin = mid + 1;
else
end = mid;
}
return matrix[begin / len2][begin % len2] == target;
}
}