【题目】
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
.
【解法一】
From the two properties, We can see that this 2D matrix is actually a 1D sorted array. We can consider this 2D matrix as an ordinary 1D matrix. Searching a target in a sorted array can be solved by binary search. The important thing here is what is the corresponding index of row and column for a index i in 1D array. For example, let start = 0, end = m * n - 1, any index i between [start, end], the corresponding index row = i / n, col = i % n. This is important and I do make this kind of mistake at my first code.
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int m = matrix.length, n = matrix[0].length;
int l = 0, r = m * n - 1;
while (l + 1 < r){
int mid = l + (r - l) / 2;
if (matrix[mid/n][mid%n] == target){
return true;
} else if (matrix[mid/n][mid%n] < target){
l = mid;
} else {
r = mid;
}
}
if (matrix[l / n][l % n] == target || matrix[r / n][r % n] == target){
return true;
}
return false;
}
【解法二】
We can first find out in which row the target is located by binary search each row's last element. Then we find out the target in that row by binary search. It is totally wrong if we by default think the target row is endrow when exiting the while loop at first step. Becuase if matrix[startrow][n-1] > target and startrow + 1 == endrow at first that they do not enter while loop, so row = startrow in this case. So we indeed need to decide the target row is startrow or endrow.
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int col = matrix[0].length - 1;
int startrow = 0, endrow = matrix.length - 1;
int row = -1;
while (startrow + 1 < endrow){
int mid = startrow + (endrow - startrow) / 2;
if (matrix[mid][col] < target){
startrow = mid;
} else if (matrix[mid][col] > target){
endrow = mid;
} else {
return true;
}
}
if (matrix[startrow][col] >= target){
row = startrow;
} else if (matrix[endrow][col] >= target){
row = endrow;
} else {
return false;
}
int i = 0;
while (i + 1 < col){
int mid = i + (col - i) / 2;
if (matrix[row][mid] == target){
return true;
} else if (matrix[row][mid] < target){
i = mid;
} else {
col = mid;
}
}
if (matrix[row][i] == target) {
return true;
}
if (matrix[row][col] == target){
return true;
}
return false;
}