面試題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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM