您的位置:首页 > Web前端

牛客《剑指Offer》 二维数组中的查找

2017-06-30 20:42 274 查看
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:从左下角开始搜索,如果当前数大于target ,向下移动,如果当前数小于target ,向后移动。
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int vrow = array.size();
int vcol = array[0].size();
int tmprow = vrow-1;
int tmpcol = 0;
while(1){
if(tmprow == -1 || tmpcol == vcol){
return false;
}
else if(array[tmprow][tmpcol] == target){
return true;
}
else if(array[tmprow][tmpcol] < target){
tmpcol++;
}
else{
tmprow--;
}
}
}
};

Codeclass Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int rowsize = array.size();
int colsize = array[0].size();
int i = 0;
int j = colsize-1;
while(i<rowsize && j>=0){
if(array[i][j]==target) return true;
else if (array[i][j]>target) j--;
else i++;
}
return false;
}
};

论坛思路:2种

2.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: