写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
给出 target = 3
,返回 true
挑战
O(log(n) + log(m)) 时间复杂度
___________________________________________________________________________
class Solution {
public:
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int> > &matrix, int target) {
if (matrix.size() == 0) return false;
int minClm = 0, maxClm = matrix.size() - 1;
int midClm = (minClm + maxClm) / 2;
while (minClm <= maxClm) {
if (matrix[midClm][0] == target) {
return true;
} else if (matrix[midClm][0] > target) {
maxClm = midClm - 1;
} else {
minClm = midClm + 1;
}
midClm = (minClm + maxClm) / 2;
}
int minRow = 0, maxRow = matrix[0].size() - 1;
int midRow = 0;
while (minRow <= maxRow) {
midRow = (minRow + maxRow) / 2;
if (matrix[midClm][midRow] == target) {
return true;
} else if (matrix[midClm][midRow] > target) {
maxRow = midRow - 1;
} else {
minRow = midRow + 1;
}
}
if (matrix[midClm][midRow] == target) {
return true;
} else {
return false;
}
}
};