题目来源
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5
, return true
.
Given target = 20
, return false
.
看到这道题一开始的想法就是二分搜索,先从左往右二分,再从上往下二分,时间复杂度是O(log(m)log(n))。
然后写好了之后才认清题目…发现根本完全就是错误的…
下次记得好好看题目!!!
没啥好想法,每一行或者每一列都二分搜索一下…
代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
auto m = matrix.size();
if (m == 0)
return false;
auto n = matrix[0].size();
if (n == 0)
return false;
for (int i=0; i<m; i++) {
int l = 0, r = n - 1, mid = 0;
while (l <= r) {
mid = (l + r) / 2;
if (matrix[i][mid] == target)
return true;
if (matrix[i][mid] < target)
l = mid + 1;
if (matrix[i][mid] > target)
r = mid - 1;
}
}
return false;
}
};
可以AC,不过比较慢,不对,是巨慢==。
想了想怎么优化,可以把行首和列首大于target的行和列去掉。
但是复杂度还是一样的。然后我又看了答案。下面是复杂度O(m+n)的方法。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
auto m = matrix.size();
if (m == 0)
return false;
auto n = matrix[0].size();
if (n == 0)
return false;
int x = 0, y = n - 1;
while (x < m && y >= 0) {
if (matrix[x][y] == target)
return true;
else if (matrix[x][y] < target)
x++;
else if (matrix[x][y] > target)
y--;
}
return false;
}
};
这种题目要好好想想如何利用好题目的条件。