offer 二维数组查找

  • 二维数组查找:

(1)C语言实现方式:

测试用例:int AA[16]={1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
bool Find1(int * target, int rows,int colums,int number) //输入的行数和列数
{
 int row=0, colum=colums-1; //实时变化的  /下标

    if (target==NULL||rows<=0||colums<=0)//保持
    {
        return false;
    }

  while(row<rows&&colum>=0)
  {

   if(*(target+row*colums+colum)==number)   //退出循环的条件
   {
    return true;
   }
   else if(number< (*(target+row*colums+colum) ))  //注意这里二维数组  乘以colums 才对
   {
       colum--;
   }
   else
   {
        row++;
   }
  }

  return false;

}

 

2.C++实现方式:

原理和上述C实现是一样的

bool Find(QVector<QVector<int> > array,int target) {

       int rowCount = array.size(); //外面这层是行    每一行里包含着各个列
       int colCount = array[0].size();

       int i,j;

       for(i=rowCount-1,j=0;i>=0&&j<colCount;)
       {
           if(target == array[i][j])
               return true;
           if(target < array[i][j])
           {
               i--;
               continue;
           }
           if(target > array[i][j])
           {
               j++;
               continue;
           }
       }
       return false;
   }
原文地址:https://www.cnblogs.com/cgy1012/p/11365407.html