问题:在一个特殊的二维数组(右边的数比左边的数大,下面的数比上面的数大)中查找是否存在某个数字。
输入:二维数组,行,列,某个数字
输出:某个数字是否存在
思路:重述下书上提供的思路,从数组的右上角(或者左下角)开始比对。
如果某个数字小于数组中选择的数,则删除该列,向左移动进行比对。
如果某个数字大于数组中选择的数,则删除该行,向下移动进行比对。
如果某个数字等于数组中选择的数,则存在,否则不存在。
代码:
#include <iostream>
using namespace std;
bool Find(int* matrix, int rows, int columns, int number)
{
bool found=false;
if(matrix!=nullptr&&rows>0&&columns>0)
{
int row=0;
int column=columns-1;
while(row<rows&&column>=0)
{
if(matrix[row*columns +column] == number)
{
found = true;
break;
}
else if(matrix[row*columns+column]<number)
{
row++;
}
else
{
column--;
}
}
}
return found;
}
int main()
{
int matrix[] = {1, 2, 8, 9, 2, 4, 9, 12, 4, 7, 10, 13, 6, 8, 11, 15};
if(Find(matrix, 4, 4, 5))
cout<<"true"<<endl;
else
cout<<"false"<<endl;
return 0;
}
复杂度分析:时间复杂度为O(rows+columns),空间复杂度为O(1)。