剑指offer 面试题4 二维数组的查找

从左下角开始比较,如果查找数更小,则上移,若更大,则右移。
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) //二维向量,连个< 之间的空格不可少,n个外层向量向量,每个向量里又
    {                                                  //存着m个int类的内层向量
        if ( array.empty())
             return false;
        int  row = array.size();    
        int  clo = array[0].size();
        int i,j;
        for ( i=row-1,j=0; i>=0 && j<clo;)  // 缺省对i,j的操作 在语句中操作。
        { if (target == array[i][j])
                return true;
            if (target < array[i][j]) 
            { i--;
                continue; 
            }
            if (target > array[i][j])
            {
                j++;
                continue;
            }
        }
        return false;
    }
}; 
从右上角开始,若查找数较小则左移,若较大,则下移。
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) 
    {
        if ( array.empty())
             return false;
        int  row = array.size();
        int  clo = array[0].size();
        int i,j;
        for ( i=0,j=clo-1; i<row && j>=0; )
        { if (target == array[i][j])
                return true;
            if (target < array[i][j])
            { j--;
                continue; 
            }
            if (target > array[i][j])
            {
                i++;
                continue;
            }
        }
        return false;
    }
}; 




猜你喜欢

转载自blog.csdn.net/qq_42209189/article/details/80315612