problem:
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) {
int rows = matrix.size();
if(rows == 0)
return false;
int cols = matrix[0].size();
if(cols == 0)
return false;
int lrow = 0;
int rrow = rows - 1;
int midrow;
while(lrow <= rrow)
{
midrow = (lrow + rrow) / 2;
if(matrix[midrow][0]==target)
return true;
else if(matrix[midrow][0] < target)
lrow = midrow + 1;
else
rrow = midrow - 1;
}
if(matrix[midrow][0] > target)
{
if(midrow == 0)
return false;
midrow--;
}
int lcol = 0;
int rcol = cols - 1;
int midcol;
while(lcol <= rcol)
{
midcol = (lcol + rcol) / 2;
if(matrix[midrow][midcol] == target)
return true;
else if(matrix[midrow][midcol] < target)
lcol = midcol + 1;
else
rcol = midcol - 1;
}
return false;
}
};