一个二维数组,每一行从左向右,从上到下都是递增数列,要求输入一个数,判断数组中是否有该数,比如以下数组查找7.
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
这个题的思路其实可以从这样从右上角的数字开始找,那么第一个数是9,比7大,那就删除这一列,接下来左移一个为8也比7大,在左移,找到2,那就开始在这列找,行数不断增加,最终找到了7.
bool find(int data[][4],int rows,int cols,int number)
{
bool found = false;
if (data != NULL && rows > 0 && cols > 0)
{
int row_start = 0;
int cols_start = cols - 1;
while (row_start < rows &&cols_start >= 0)
{
if (data[row_start][cols_start] == number)
{
found = true;
break;
}
else if (data[row_start][cols_start] > number)
{
cols_start--;
}
else
row_start++;
}
}
return found;
}