题目:
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.
做法:分治
对于矩阵中的任何一个数x,如果target<=x,则target不会存在于x右下角的子矩阵中;若target>x,则target不会存在于x左上角的子矩阵中。
所以由T(n*m) = 3*T(n*m/4),可知该算法复杂度为O((n*m)^0.8),已经可以卡时通过这道题了。
class Solution {
public:
bool searchMatrix(vector< vector<int> >& matrix, int target) {
int x1 = 0, x2 = matrix.size() - 1;
int y1 = 0, y2 = matrix[0].size() - 1;
return dsearchMatrix(matrix, target, x1, y1, x2, y2);
}
bool dsearchMatrix(vector< vector<int> >& matrix, int target, int x1, int y1, int x2, int y2) {
//cout << x1 << " "<< x2 << " " << y1 << " " << y2 << endl;
if (x1 > x2 || y1 > y2 || target < matrix[x1][y1] || target > matrix[x2][y2]) return false;
if (x1 == x2 && y1 == y2) return target == matrix[x1][y1];
int x = (x1 + x2) / 2;
int y = (y1 + y2) / 2;
if (target <= matrix[x][y]) return dsearchMatrix(matrix, target, x1, y1, x, y) | dsearchMatrix(matrix, target, x + 1, y1, x2, y2) | dsearchMatrix(matrix, target, x1, y + 1, x, y2);
else return dsearchMatrix(matrix, target, x + 1, y + 1, x2, y2) | dsearchMatrix(matrix, target, x + 1, y1, x2, y2) | dsearchMatrix(matrix, target, x1, y + 1, x, y2);
}
};
上面的方法写起来比较麻烦,更简单的是对每一行(列)通过二分法查找target。
这样的复杂度是O(nlogm),nlogn < n^1.6。
测试用时也证明了这点。
class Solution {
public:
bool searchMatrix(vector< vector<int> >& matrix, int target) {
for (int i = 0; i < matrix.size(); i++) {
vector<int>::iterator it = lower_bound(matrix[i].begin(), matrix[i].end(), target);
if (it != matrix[i].end() && *it == target) return true;
}
return false;
}
};