標籤:返回 12px out ace 方法 完成 ber 劍指offer ext
題目:在一個二維數組中,每一行都按照從左至右遞增的順序,每一列都按照從上到下遞增的順序排序,完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否有該函數。
如二維數組:
| 1 |
2 |
8 |
9 |
| 2 |
4 |
9 |
12 |
| 4 |
7 |
10 |
13 |
| 6 |
8 |
11 |
15 |
尋找數字7,存在返回true;尋找數字5,不存在,返回false;
處理方法:
從最右上方的數字開始,如果尋找數小於該數,則尋找數一定位於該數左側,排除該列,繼續尋找左側剩下的矩陣;
如果尋找數大於該數,則尋找數一定位於該數下側,排除該行,繼續尋找下側剩下的矩陣,以此類推繼續從剩下矩陣的右上方數字開始尋找;
如果尋找數字等於該數,則返回true;
如果已無矩陣剩下且仍未找到,則返回false。
代碼:
bool Find(int *matrix, int rows, int columns, int number) { bool found = false; int row = 0, column = columns-1; if (matrix != NULL && rows > 0 &&columns >0) { 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;}
完整測試代碼:
#include <iostream>#include <stdio.h>using namespace std;bool Find(int *matrix, int rows, int columns, int number) { bool found = false; int row = 0, column = columns-1; if (matrix != NULL && rows > 0 &&columns >0) { while(row < rows && column >=0) { if(matrix[row*columns+column] == number) { found = true; break; } else if (matrix[row*columns+column] > number) { --column; } else { ++row; } } } if(found) cout << "The number found in row: " << row+1 <<", column: " << column+1 << ‘.‘ << endl; else cout << "The number is not found." << endl; cout << "------------------------------" << endl; return found;}void Test(int* matrix, int rows, int columns, int number) { cout << "-------The input matrix is: ------" << endl; for(int r = 0; r< rows; r++) { for(int c = 0; c < columns; c++) { if(r==rows) break; cout << matrix[r*columns+c] << ‘\t‘; if(c==columns-1) { c = -1; ++r; cout << endl; } } } cout << endl << "The number to find: " << number << ‘.‘ << endl; Find(matrix, rows, columns, number);}int main() { int matrix[][4] = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}}; Test((int*)matrix, 4, 4, 7); Test((int*)matrix, 4, 4, 5); Test((int*)matrix, 4, 4, 1); Test((int*)matrix, 4, 4, 15); Test((int*)matrix, 4, 4, 0); Test((int*)matrix, 4, 4, 16); Test((int*)matrix, 0, 0, 16); return 0; }
參考資料:《劍指offer名企面試官精講典型編程題》
C++二維數組尋找題