题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
- 当我们需要解决一个复杂的问题时,一个很有效的办法就是从一个具体的问题入手,通过分析简单具体的例子,试图寻找普遍的规律。
从右上角开始
/* 从右上角开始查找 */
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] > nubmer){
--column;
}else{
++row;
}
}
}
return found;
}
- 考查应聘者对二维数组的理解及编程能力。二维数组在内存中占据连续的空间。在内存中从上到下存储各行元素,在同一行中按照从左到右的顺序存储。因此我们可以根据行号和列号计算出相对于数组首地址的偏移量,从而找到对应的元素。
- 考查应聘者分析问题的能力。当应聘者发现问题比较复杂时,能不能通过具体的例子找出其中的规律,是能否解决这个问题的关键所在。
/* 从左下角开始 */
bool Find(int* matrix, int rows, int columns, int number)
{
bool found = false;
if((matrix != NULL) && (rows > 0) && (columns > 0)){
int row = rows - 1;
int column = 0;
while((row >= 0) && (column < columns)){
if(matrix[row*columns + 1] == number){
found = true;
break;
}else if(matrix[row*columns + 1] > number){
--row;
}else{
--column;
}
}
}
return found;
}