本题要求如下:
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
.
本题最开始秒想出一种O(mn)的算法,就是把matrix完全展开,就是一个sorted array,然后用binary search,提交之后一次通过了,不过一看这是medium题,感觉怪怪的。。。于是又想了一会儿,想出一种O(log(m)+log(n))的方法。思路也是比较简单,但是处理边界条件花了我一点时间。
直接上代码:
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
int row = -1;
int low = 0;
int high = m - 1;
int mid = 0;
while (low <= high) {
mid = (high + low) / 2;
if (matrix[mid][0] == target)
return true;
else if (matrix[mid][0] > target)
high = mid - 1;
else {
if (matrix[mid][n-1] >= target) {
row = mid;
break;
}
else
low = mid + 1;
}
}
if (row == -1)
return false;
low = 1;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (matrix[row][mid] == target)
return true;
else if (matrix[row][mid] > target)
high = mid - 1;
else
low = mid + 1;
}
return false;
}
};
算法解释:
本题用了两次binary search:
1,第一次复杂一点,需要处理边界条件,如果matrix[mid][0]比target小的话,不能单纯的直接low = mid + 1,因为即使这样target也可能在mid这一行,所以需要检查matrix[mid][n-1]是否大于target,如果大于target,则返回这一行为row,否则按binary search的通常步骤处理
2,如果第一次binary search中没有找到target > matrix[mid][0], target < matrix[mid][n-1]的那行,即该target < matrix[0][0]或者 > matrix[m-1][n-1],无论是哪种可能,在循环中都不会对row赋值,这种情况就直接判定为false
3,第二次在确定的行内搜索就是普通的binary search