题目
题解
- 从右上角开始遍历——找规律
- 二分查找,分别查找行和列
代码
// class Solution {
// public:
// bool searchMatrix(vector<vector<int>>& matrix, int target) {
// if(matrix.size()==0)
// return false;
// int col=matrix[0].size()-1;
// int row=0;
// while(row<matrix.size()&&col>=0){
// if(target<matrix[row][col])
// col--;
// else if(target>matrix[row][col])
// row++;
// else
// return true;
// }
// return false;
// }
// };
class Solution {
private:
bool binarySearch(vector<vector<int>>& matrix, int target, int start, bool vertical) {
int l = start;
int r = vertical ? matrix[0].size()-1 : matrix.size()-1;
while (r >= l) {
int mid = (l + r)/2;
if (vertical) { // searching a column
if (matrix[start][mid] < target)
l = mid + 1;
else if (matrix[start][mid] > target)
r = mid - 1;
else
return true;
}
else { // searching a row
if (matrix[mid][start] < target)
l = mid + 1;
else if (matrix[mid][start] > target)
r = mid - 1;
else
return true;
}
}
return false;
}
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size()== 0)
return false;
for (int i = 0; i < min(matrix.size(), matrix[0].size()); i++) {
bool vertical = binarySearch(matrix, target, i, true);
bool horizontal= binarySearch(matrix, target, i, false);
if (vertical || horizontal)
return true;
}
return false;
}
};