|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-4-5 10:40 编辑
题目描述:
- 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
-  
- 示例:
- 现有矩阵 matrix 如下:
- [
- [1, 4, 7, 11, 15],
- [2, 5, 8, 12, 19],
- [3, 6, 9, 16, 22],
- [10, 13, 14, 17, 24],
- [18, 21, 23, 26, 30]
- ]
- 给定 target = 5,返回 true。
- 给定 target = 20,返回 false。
-  
- 限制:
- 0 <= n <= 1000
- 0 <= m <= 1000
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- #include <vector>
- #include <iostream>
- using namespace std;
- bool solution(vector<vector<int> >& input, int target){
- if(input.size() == 0 || input[0].size() == 0) return false;
- //start point
- int a = input.size() - 1;
- int b = 0;
- while(a >= 0 && b <= input[0].size()-1){
- if(input[a][b] == target) return true;
- if(input[a][b] > target){
- a--;
- continue;}
- if(input[a][b] < target) {
- b++;
- continue;}
- }
- return false;
- }
- int main(void){
- vector<vector<int> > input;
- int n, m;
- cout << "please send a number for row" << endl;
- cin >> n;
- input.resize(n);
- cin.clear();
- cout << "please send a number for column" << endl;
- cin >> m;
- cin.clear();
- cout << "please send number for matrix(n*m)" << endl;
- int number;
- for(int i = 0; i < n; i++){
- for(int j = 0; j < m; j++){
- cin >> number;
- input[i].push_back(number);
- }
- }
- for(int i = 0; i < n; i++){
- for(int j = 0; j < m; j++){
- cout << input[i][j] << " ";
- }
- cout << endl;
- }
- cout << endl;
- cin.clear();
- int target;
- cin >> target;
- bool result = solution(input, target);
- cout << result << endl;
- return 0;
- }
复制代码
参考链接:https://www.bilibili.com/video/B ... 6509475985055900873
https://bbs.csdn.net/topics/392144947
注意事项:
1.边界的确定
2.while()里的条件如果把符号全部换成!=则存在遗漏情况的问题。
3.从矩阵的右上角或左下角开始作为初始点。 |
|