【描述】:

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

【测试】:


样例输入

2
3
1 3 5
2 4 7
6 8 9
3
1
7
10
2
1 1
1 1
1
1

样例输出

1 1
2 3
-1
1 2

【思路】:

【剑指offer之二维数组中的查找 】_#include

【代码】:


/*********************** 
【Problem】剑指offer之二维数组中的查找
Author:herongwei
Time:2017/5/10 17:22
language:C++

***********************/
#include <bits/stdc++.h>
#include <algorithm>
#define rep(i,k,n) for(int i=k;i<=n;++i)
#define rep2(i,k,n) for(int i=k;i>=n;--i)
using namespace std;
typedef long long LL;
const int maxn = 1e3+233;
const LL MOD = 999999997;
const int inf= 0x3f3f3f3f;
int dir4[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
int dir8[8][2]= {{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
inline int read(){
int c=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){c=c*10+ch-'0';ch=getchar();}
return c*f;
}
int mat[maxn*maxn],cnt,ret,ans,tp;
int t,n,m,val,fi,fj,tot=0;

/*
【思路】:选取右上角的一个数,这个数是该列的最小和改行的最大,则用key与这个数比较,
相等,则就是这个数;
若key>该数,则排除该数所在的行;
若key<该数,则排除该数所在的列。
结果是==或查找范围为空
*/
bool find_num(int *mat,int row,int col,int key){
bool found=false;
int x=0,y=col-1;
while(x>=0&&x<row&&y>=0&&y<col){
if(mat[x*col+y]==key){
fi=x;
fj=y;
found=true;
break;
}else{
if(mat[x*col+y]>key){
--y;
}else{
++x;
}
}
}
return found;
}

int main(){
// freopen("in.txt","r",stdin);
t=read();
while(t--){
memset(mat,0,sizeof(mat));
n=read();
rep(i,0,n*n-1)mat[i]=read();
m=read();
rep(i,1,m){
val=read();
if(find_num(mat,n,n,val)) printf("%d %d\n",fi+1,fj+1);
else puts("-1");
}
}
return 0;
}



牛客网版本:

class Solution
{
public:
bool Find(int target, vector<vector<int> > array)
{
int row=array.size();
int col=array[0].size();
int x=0,y=col-1;
if(!array.empty()&&row>0&&col>0)
{
while(x>=0&&x<row&&y>=0&&y<col)
{
if(array[x][y]==target)
{
return true;
break;
}
else if(array[x][y]>target)--y;
else ++x;
}
return false;
}
return false;
}
};