时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 热度指数:1762562
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
// ConsoleApplication8.cpp : 定义控制台应用程序的入口点。
//
#include<iostream>
#include <cstdio>
#include<vector>
using namespace std;
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int i = 0, j = 0;
int st = 0;
if (array.empty())return false;
int len = array.size();
int size = array[0].size();
for (i = len - 1; i >= 0; i--){
if (array[i].empty())continue;
for (j = size - 1; array[i][j]>target&&j >= st; j--);
if (j == (st - 1) && array[i][j + 1]>target)continue;
if (array[i][j] == target)return true;
if (j == size - 1)return false;
if (array[i][j]<target){
st = j + 1;
continue;
}
}
return false;
}
};
int _tmain()
{
int m = 9;
int n = 10;
vector<vector<int> > array(m); //这个m一定不能少//vector<int> array[m];
//初始化一个m*n的二维数组
for (int i = 0; i<m; i++)
{
array[i].resize(n);
}
//遍历赋值
for (int i = 0; i < array.size(); i++)
{
for (int j = 0; j < array[0].size(); j++)
{
array[i][j] = (i +j);
}
}
Solution x;
if (x.Find(15, array)){
cout << "ok" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
//int i = 0, j = 0;
//vector< vector<int> > maze(8, vector<int>(12, 0));
//int A[8][12] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
//{ 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1 },
//{ 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1 },
//{ 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1 },
//{ 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1 },
//{ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1 },
//{ 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
//{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
//};
//https://blog.csdn.net/qq_31918961/article/details/90109988
//https ://blog.csdn.net/weixin_42187898/article/details/93520211