1、前言
题目描述2、思路
思路很简单,就是普通二分查找的思路,先确定行,再确定列,但是细节是魔鬼
3、代码
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
// 先确定在哪一行
int m = matrix.length, n = matrix[0].length;
int l = 0, r = m - 1;
while(l < r){
int mid = (l + r + 1) / 2;
if(matrix[mid][0] <= target){
l = mid;
}else {
r = mid - 1;
}
}
int row = r;
if(matrix[row][0] == target){
return true;
}
if(matrix[row][0] > target){
return false;
}
// 后确定在哪一列
l = 0;
r = n - 1;
while(l < r){
int mid = (l + r + 1) / 2;
if(matrix[row][mid] <= target){
l = mid;
}else {
r = mid - 1;
}
}
int column = r;
return matrix[row][column] == target;
}
}
网友评论