-
题目描述:
-
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
-
输入:
-
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为两个整数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; }