- 題目描述:
-
在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
- 輸入:
-
輸入可能包含多個測試樣例,對於每個測試案例,
輸入的第一行爲兩個整數m和n(1<=m,n<=1000):代表將要輸入的矩陣的行數和列數。
輸入的第二行包括一個整數t(1<=t<=1000000):代表要查找的數字。
接下來的m行,每行有n個數,代表題目所給出的m行n列的矩陣(矩陣如題目描述所示,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。
- 輸出:
-
對應每個測試案例,
輸出”Yes”代表在二維數組中找到了數字t。
輸出”No”代表在二維數組中沒有找到數字t。
- 樣例輸入:
-
3 3
5
1 2 3
4 5 6
7 8 9
3 3
1
2 3 4
5 6 7
8 9 10
3 3
12
2 3 4
5 6 7
8 9 10
- 樣例輸出:
-
Yes
No
No
解決思路:由於每行每列的數據都是遞增,那麼我們很容易想到二分查找,但是,這個是個二維數組,所以可以考慮先找到t可能出現的行(列),然後在二分的查找所在的列(行)
#include <iostream> #include <fstream> #include <vector> #include <cstdio> using namespace std; /* ac.jobdu.com 題目1384:二維數組中的查找 */ typedef vector<vector<int> > mat; int bsearch1(const mat& mt, const int& row, const int& col, const int& key ) { int low = 0, high = row - 1, mid = 0; while (low <= high) { mid = low + ((high - low) >> 1); if (key < mt[mid][col - 1]) { high = mid; } else { low = mid + 1; } if (low == high) { return low; } } return low; } bool bsearch2 (const mat& mt, const int& row_pos, const int& col, const int & key) { int low = 0, high = col - 1, mid = 0; while (low <= high ) { mid = low + ((high - low ) >> 1); if (key > mt[row_pos][mid]) { low = mid + 1; } else if (key < mt[row_pos][mid]) { high = mid - 1; } else { return true; } } return false; } bool exists (const mat& m, const int & nrow, const int& ncol, const int & key) { return bsearch2(m, bsearch1(m, nrow, ncol, key), ncol, key); } int main() { //ifstream cin ("input.txt"); int row, col, key, t; mat m; while (scanf ("%d %d", &row, &col) == 2) { scanf ("%d", &key); for (int i = 0; i< row; ++i ) { vector <int> v; for (int j = 0; j < col; ++j ) { scanf ("%d", &t); v.push_back(t); } m.push_back(v); } if (exists(m, row, col, key)) printf("Yes\n"); else printf("No\n"); m.clear(); } return 0; }