LeetCode 74 搜索二维矩阵
程序员文章站
2022-05-21 16:13:43
...
// 二分,当成一维数组,下标转换
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length;
if (n == 0) return false;
int m = matrix[0].length;
int l = 0;
int r = n * m;
int mid;
int row;
int col;
while(l < r){
mid = (l + r) / 2;
row = mid / m;
col = mid % m;
if (target < matrix[row][col]) {
r = mid;
}else if (target == matrix[row][col]){
return true;
}else {
l = mid + 1;
}
}
return false;
}
}
下一篇: 连通图练习总结