这道题乍一看,和做过的搜索二维矩阵Ⅱ类似,用之前的代码也能通过,但忽略掉了每行的第一个整数大于前一行的最后一个整数这个条件。可以使用两次二分法来解决这道题目
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size() - 1, n = matrix[0].size() - 1;
int left = 0, right = m, row = 0;
if(target == matrix[left][n] || target == matrix[right][n]){
return true;
}
while(left < right){
int mid = left + (right - left)/2;
if(target < matrix[mid][n]){
right = mid;
}else if(target > matrix[mid][n]){
left = mid + 1;
row = left;
}else{
return true;
}
}
int newleft = 0, newright = n;
while(newleft < newright){
int newmid = newleft + (newright - newleft)/2;
if(target < matrix[row][newmid]){
newright = newmid;
}else if(target > matrix[row][newmid]){
newleft = newmid + 1;
}else{
return true;
}
}
return false;
}
};
标签:right,matrix,int,矩阵,mid,二维,搜索,target,left
From: https://blog.csdn.net/why_12134/article/details/141144292