牛客网剑指Offer——二维数组中的查找

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

方法一:
直接暴力搜索

方法二:
按行搜索,如果第i行的第1个数小于等于target,且最后一个数大于等于target,则搜索这一行,否则直接跳过这一行

class Solution {
public:
    bool Find(int target, vector > array) {
        if( array.empty() )
            return false;
         
        for( int i=0;i= target )
                for( int j=0;j

方法三:
从二维数组的右上角开始搜索,即第一行的最后一个数,记作array[row][col],row = 0,col = array[0].size()-1,如果相等则返回True,如果小于target则row++,如果大于target则col--

class Solution {
public:
    bool Find(int target, vector > array) {
        if( array.empty() )
            return false;
         
        int row = 0;
        int col = array[0].size()-1;
         
        while( row < array.size() && col >= 0 )
        {
            if( array[row][col] == target )
                return true;
            else if( array[row][col] > target )
                col--;
            else if( array[row][col] < target )
                row++;
        }
         
        return false;
    }
};

你可能感兴趣的:(牛客网剑指Offer——二维数组中的查找)