采用官方解法。
时间复杂度:O(n+m)O(n+m)。访问到的下标的行最多增加 n 次,列最多减少 m 次,因此循环体最多执行 n + m 次。 空间复杂度:O(1)O(1)。
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0 || matrix[0].size() == 0 ) return false;
int rows = matrix.size(), cols = matrix[0].size();
int row = 0, col = cols-1;
bool found = false;
while(row <= rows-1 && col >= 0){
//每次选取右上角进行比较
if (matrix[row][col] > target){
--col; continue;
}
else if (matrix[row][col] < target){
++row; continue;
}
else if (matrix[row][col] == target) {
found = true;
break;
}
}
return found;
}
};