使用二分查找来解决该问题。这道题使用二分查找算法的核心点在于一维索引 mid
对应的二维矩阵位置换算公式 matrix[mid / n][mid % n]
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0;
int right = rows * cols - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
int midValue = matrix[mid / cols][mid % cols];
if(midValue == target) {
return true;
} else if(midValue > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return false;
}
}