面试题3 ----二维数组中的查找

题目

        在一个二维数组中,每一行都依照从左到右递增的顺序排序。每一列都依照从上到下递增的顺序排序。请完毕一个函数。输入这种一个二维数组和一个整数,推断数组中是否含有该整数。





在剩下的两行两列4个数字中,位于右上角的刚好就是我们要查找的数字7。于是查找过程就能够结束了。


矩阵的加阴影背景的区域是下一步查找的范围。代码例如以下:


bool Find(int* matrix,int  rows,int columns,int number)
{
bool found = false;
if (matrix != NULL && 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)
--column;
else
++row;
}
}
return found;
}

以上是每一次选取数组查找范围内的右上角数字,也能够选取左下角数字(可是不能选择左上角或者右下角)。


posted @ 2016-03-12 13:37  blfshiye  阅读(114)  评论(0编辑  收藏  举报