class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (const auto& row: matrix) {
auto it = lower_bound(row.begin(), row.end(), target);
if (it != row.end() && *it == target) {
return true;
}
}
return false;
}
};
auto it = lower_bound(row.begin(), row.end(), target);
-
row:一个有序的 vector(如vector<int>) -
lower_bound:二分查找算法,返回一个迭代器 -
auto:自动推导迭代器类型 -
it:指向第一个>= target的元素 -
有序数组中查找第一个大于等于 target 的元素。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int x = 0, y = n - 1;
while (x < m && y >= 0) {
if (matrix[x][y] == target) {
return true;
}
if (matrix[x][y] > target) {
--y;
}
else {
++x;
}
}
return false;
}
};
从右上角开始查找