剑指offer:二维数组,行按照从左到右递增的顺序排序,列按照从上到下的顺序进行排序
思路:选取右上角或者左下角的数字和要查找的数字作比较,建议画图示意,思路非常清晰
#include<iostream>
using namespace std;
bool Find(int *matrix, int rows, int cols, int number)
{
bool found = false;
if (matrix != NULL &&rows > 0 && cols > 0)
{
int row = 0;
int col = cols - 1;
while (row < rows && cols >= 0)
{
if (matrix[row*cols + col] == number)
{
found = true;
break;
}
else if (matrix[row*cols + col]>number)
--col;
else
++row;
}
}
return found;
}
int main()
{
bool flag = false;
int row=0,col=0,num=0;
int test[3][3];
cout << "输入如下:" << endl;
cin >> row >> col >> num;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> test[i][j];
}
}
flag = Find(*test, row, col, num);
if (flag == false)
cout << "false" << endl;
else
cout << "true" << endl;
}