面试题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 }

 

转载于:https://www.cnblogs.com/jostree/p/4249122.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值