题目链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/ 题目如下: 好理解的一种:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int row=matrix.size();
if(row==0) return false;
int col=matrix[0].size();
int i=row-1,j=0;
while(i>=0&&j<col){
if(matrix[i][j]==target) return true;
else if(matrix[i][j]>target) --i;
else if(matrix[i][j]<target) ++j;
}
return false;
}
};
不太好理解的一种:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.size()==0||matrix[0].size()==0) return false;
int row=matrix.size(),col=matrix[0].size();
int j=row-1;
for(int i=0;i<col;){
for(;j>=0;j--){
if(matrix[j][i]==target) return true;
else if(matrix[j][i]<target) {
i++;
j==row-1?row-1:j++;
break;
}
}
if(j==-1) i++;
}
return false;
}
};
|