Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return
true.
二分查找。
bool searchMatrix(vector<vector<int> > &matrix, int target) { //C++
int rows = matrix.size();
if(rows == 0)
return false;
int cols = matrix[0].size();
int low = 0, high = rows*cols-1;
int i,j;
while(low <= high)
{
int mid = (low + high)/2;
i = mid/cols;
j = mid%cols;
if(matrix[i][j] == target)
return true;
if(matrix[i][j] < target)
low = mid +1;
else high = mid -1;
}
return false;
}原文地址:http://blog.csdn.net/chenlei0630/article/details/41288255