题目:
代码:
public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int columns = matrix[0].length;
// 先找到行,行为当前行第一列<target,当前行+1行,第一列>target
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == target) {
return true;
} else if (i + 1 == rows || matrix[i + 1][0] > target && matrix[i][0] < target) { // 这里从下标0开始,遍历到最后一行数组下标越界问题耗费了很长时间,注:最后一行 i+1==rows直接进行二分
int left = 0, right = columns - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (matrix[i][mid] == target) {
return true;
} else if (matrix[i][mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
} else {
// continue;
}
}
return false;
}