Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:Integers in each row are sorted from left to right. The first integer
of each row is greater than the last integer of the previous row. For
example,Consider the following matrix:
[ [1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
常规解答,比较麻烦,要考虑很多边界值的问题
class Solution {
public://自己想的解法,还蛮复杂的。。。。因为要考虑的测试用例太多了。。。一不小心就会忽略某种情况。。。。
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty()||matrix[0].empty()) return false;
int m=matrix.size(),n=matrix[0].size(),i=0,j=0;
while (i<m){//确定行
if(matrix[i][0]<target) i++;
else if(matrix[i][0]==target) return true;
else {i=max(0,i-1); break;}
}
if(i==m) i--;
while(j<n){//确定列
if(matrix[i][j]<target) j++;
else if(matrix[i][j]==target) return true;
else return false;
}
return false;//搜索到确定行的最后面也没有发现,返回错误
}
};
大牛思路:// treat the matrix as an array, just taking care of indices
bool searchMatrix(vector<vector<int>>& matrix, int target) {
// treat the matrix as an array, just taking care of indices
// [0..n*m]
// (row, col) -> row*n + col
// i -> [i/n][i%n]
if(matrix.empty() || matrix[0].empty())
{
return false;
}
int m = matrix.size(), n = matrix[0].size();
int start = 0, end = m*n - 1;
while(start <= end)//二分查找的思想
{
int mid = start + (end - start)/2;
int e = matrix[mid/n][mid%n];//array索引转换为矩阵的公式[mid/n][mid%n]
if(target < e)
{
end = mid - 1;
}
else if(target > e)
{
start = mid + 1;
}
else
{
return true;
}
}
return false;
}