- 搜索二维矩阵 II
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
二分法:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (auto row : matrix) {
auto itr = lower_bound(row.begin(), row.end(), target);
if (itr != row.end() && *itr == target) {
return true;
}
}
return false;
}
};
z字形查找法:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
int x = 0;
int y = m - 1;
while (x < n && y >= 0)
{
if (matrix[x][y] == target) {
return true;
}
if (matrix[x][y] > target) {
--y;
} else {
++x;
}
}
return false;
}
};