面试题3:有序矩阵中查找数字

作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4249122.html

题目描述:在一个二维数组中,每行数字从左到右递增,每列数字从上到下递增,给定一个整数,判断该数是否存在于二位数组之中.

解决方法:

我们可以从右上角开始:

如果该数恰好等于要查找的数,则返回true.

如果该数小于要查找的数,说明这一行的数都小于要查找的数,于是删除第一行继续查找.

如果该数大于要查找的数,说明这一列都大于要查找的数,于是删除这一列继续查找.

最后如果都没有找到,则返回false.

需要注意的是,在c语言中,二维数组作为参数传递的时候需要注明第二维的大小例如find(int a[][4]),但是这样就会把数组第二维大小定死,

所以使用了一位数组代替二维数组而把寻址方式由a[x][y]变为a[x*column+y]的方式,并需要把二位数组的地址进行强制转换,代码如下:

 

 1 #include <stdio.h>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 bool find(int * Matrix , int rows, int columns, int number)
 7 {
 8     bool found = false;
 9     if( Matrix != NULL && rows > 0 && columns > 0 )
10     {
11         int row = 0;
12         int column = columns - 1;
13         while( row < rows && column >= 0 )
14         {
15             if( Matrix[row * columns + column] == number )
16             {
17                 found = true;
18                 break;
19             }
20             else if( Matrix[row * columns + column] < number )
21             {
22                 ++row;
23             }
24             else
25             {
26                 --column;
27             }
28         }
29     }
30     return found;
31 }
32 
33 int main(int argc, char *argv[])
34 {
35     int Matrix[4][4] =  
36     {
37         {1, 2, 8, 9}, 
38         {2, 4, 9, 12}, 
39         {4, 7, 10, 13}, 
40         {6, 8, 11, 15}
41     };
42     cout<<find((int*)Matrix, 4, 4, 6)<<endl;
43 }

 

posted @ 2015-01-25 22:44  jostree  阅读(1473)  评论(7编辑  收藏  举报