O(m+n)
二分法可以从左下开始 --》 右上
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length < 1 || matrix[0].length <1) {
return false;
}
int col = matrix[0].length-1;
int row = 0;
while(col >= 0 && row <= matrix.length-1) {
if(target == matrix[row][col]) {
return true;
} else if(target < matrix[row][col]) {
col--;
} else if(target > matrix[row][col]) {
row++;
}
}
return false;
}
public int searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int col = 0;
int row = matrix[0].length - 1;
int count = 0;
while (col < matrix.length && row >=0) {
if (matrix[col][row] < target) {
col++;
}
else if (matrix[col][row] > target) {
row--;
}
else {
count++;
row--;
col++;
}
}
return count;
}