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

来源:互联网 发布:淘宝多店铺管理软件 编辑:程序博客网 时间:2024/06/04 23:39

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

思路:从左下角开始搜索,如果当前数大于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--;            }        }    }};



论坛思路:2种

1.把每一行看成有序递增的数组,
利用二分查找,
通过遍历每一行得到答案,
时间复杂度是nlogn
publicclassSolution {
    publicbooleanFind(int[][] array,inttarget) {
         
        for(inti=0;i<array.length;i++){
            intlow=0;
            inthigh=array[i].length-1;
            while(low<=high){
                intmid=(low+high)/2;
                if(target>array[i][mid])
                    low=mid+1;
                elseif(target<array[i][mid])
                    high=mid-1;
                else
                    returntrue;
            }
        }
        returnfalse;
 
    }
}
 
2.另外一种思路是:
利用二维数组由上到下,由左到右递增的规律,
那么选取右上角或者左下角的元素a[row][col]与target进行比较,
当target小于元素a[row][col]时,那么target必定在元素a所在行的左边,
即col--;
当target大于元素a[row][col]时,那么target必定在元素a所在列的下边,
即row++;
publicclassSolution {
    publicbooleanFind(int[][] array,inttarget) {
        introw=0;
        intcol=array[0].length-1;
        while(row<=array.length-1&&col>=0){
            if(target==array[row][col])
                returntrue;
            elseif(target>array[row][col])
                row++;
            else
                col--;
        }
        returnfalse;
 
    }
}

2.

原创粉丝点击