题目链接:力扣
解题思路:因为矩阵整体上是有序的,所以可以先二分查找target在哪一行中,然后再次二分查找target在当前行的哪一列中。
具体算法如下:
- 对行使用二分查找:
- 初始值:
- int m = matrix.length
- int n = matrtix[0].length
- int rowLeft = 0;
- int rowRight = 0;
- boolean result = false:记录是否找到目标
- 如果rowLeft < rowRight,则循环使用二分进行查找:
- rowMid = (rowLeft + rowRight)/2
- 如果 matrix[rowMid][n-1] < target:当前行最后一个元素比target还小,令rowLeft = rowMid+1
- 如果 matrix[rowMid][0] > target:当前行的第一个元素比target还大,令rowRight = rowMid
- 否则,说明,如果target存在,则target肯定在当前这一行:
- 初始值:
- colLeft = 0
- colRight = n
- 如果colLeft < colRight,则对这一行再次循环使用二分查找:
- colMid = (colLeft + colRight)/2
- 如果matrix[rowMid][colmid] > target:则colRight = colMid
- 如果 matrix[rowMid][colmid] < target:则colLeft = colMid++1
- 否则,说明matrix[rowMid][colmid] = target:
- 令result = true
- break退出循环
- break退出外层循环
- 初始值:
- return result;
- 初始值:
AC代码
class Solution {
public static boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int rowLeft = 0;
int rowRight = m;
boolean result = false;
while (rowLeft < rowRight) {
int rowMid = (rowLeft + rowRight) / 2;
if (matrix[rowMid][n - 1] < target) {
rowLeft = rowMid + 1;
} else if (matrix[rowMid][0] > target) {
rowRight = rowMid;
} else {
int colLeft = 0;
int colRight = n;
while (colLeft < colRight) {
int colMid = (colLeft + colRight) / 2;
if (matrix[rowMid][colMid] > target) {
colRight = colMid;
} else if (matrix[rowMid][colMid] < target) {
colLeft = colMid + 1;
} else {
result = true;
break;
}
}
break;
}
}
return result;
}
}