搜索二维矩阵
问题:
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
- 每行中的整数从左到右按升序排列。
- 每行的第一个整数大于前一行的最后一个整数。
思路:
- 先进行搜索,再进行列搜索。
- 由于二维数组元素升序排列,所以都采用从后往前搜索,比较方便确定 target 所在行
- 可以采用二分查找的方法使时间复杂度从 mn 降到 log(mn) 。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
auto m = matrix.size();
auto n = matrix[0].size();
while(m-- > 0) { // 搜索行
if(matrix[m][0] <= target) {
while(n-- > 0) { // 搜索列
if(matrix[m][n] == target) return true; // 存在返回 true
if(!n) return false; // 所在行没有返回 false
}
}
}
return false; // 首元素大于 target 返回 false
}
};
时间复杂度:O(mn)
空间复杂度:O(1)
// 二分查找实现
class Solution {
public:
bool searchMatrix(vector<vector<int>> matrix, int target) {
auto row = upper_bound(matrix.begin(), matrix.end(), target, [](const int b, const vector<int> &a) {
return b < a[0];
});
if (row == matrix.begin()) {
return false;
}
--row;
return binary_search(row->begin(), row->end(), target);
}
};
时间复杂度:O(log(mn))
空间复杂度:O(1)