方法一:从右上角开始走,时间复杂度为 $O(n + m)$
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = 0, col = matrix[0].size() - 1;
while (row < matrix.size() && col >= 0)
{
if (matrix[row][col] == target) return true;
else if (matrix[row][col] < target) row ++ ;
else col -- ;
}
return false;
}
};
方法二:二分法,时间复杂度为 $O(log(n * m))$
将整个数组看成一个升序序列
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size(), m = matrix[0].size();
int l = 0, r = n * m - 1;
while (l <= r) //注意这里必须是小于等于
{
int mid = (l + r) >> 1;
int mid_val = matrix[mid / m][mid % m]; //根据 mid 计算行列坐标
if (mid_val == target) return true;
else
{
if (mid_val > target) r = mid - 1;
else l = mid + 1;
}
}
return false;
}
};