https://leetcode.cn/problems/search-a-2d-matrix/description/?envType=study-plan-v2&envId=top-100-liked
思路:先按行二分,再按列进行二分。即先找到对应的行,再找对应的列。
对于这种判断是否存在某个数,记得while(left<=right)要加=,不然循环完了还要特判等于不等于,因为最后一次left=right是否已经跳出了循环
具体二分查找的写法可以看我之前的文章:https://blog.csdn.net/qq_45816864/article/details/134752708?spm=1001.2014.3001.5501
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
//思路也比较明显,先按行二分,再按列进行二分
//我们先对行进行二分
int n = matrix.length;
int m = matrix[0].length;
int high = n-1;
int low = 0;
int left = 0;
int right = m-1;
//通过最后一列定位最大的数字
while(low<high){
int mid = (low+high)/2;
if(matrix[mid][right]>=target)high = mid;
else low = mid+1;
}
//while(left<=right)后面就不需要特判
while(left<right){
int mid = (left+right)/2;
if(matrix[low][mid]==target)return true;
else if(matrix[low][mid]>target) right= mid-1;
else left = mid+1;
}
//这里有一个细节最后一次mid的赋值之后是不会判断是否等于的,这里要补上
//或者前面外while(<=)那里可以加一个等于号
if(matrix[low][left]==target) return true;
return false;
}
}