【剑指offer之二维数组中的查找 】
来源:互联网 发布:剑网3秀萝捏脸数据图片 编辑:程序博客网 时间:2024/05/22 11:58
【描述】:
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
【测试】:
样例输入
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
【代码】:
/*********************** 【Problem】剑指offer之二维数组中的查找 Author:herongwei Time:2017/5/10 17:22 language:C++ http://blog.csdn.net/u013050857 ***********************/ #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; }};
0 0
- 剑指offer之二维数组中的查找
- 剑指Offer之二维数组中的查找
- 剑指Offer之 - 二维数组中的查找
- 剑指offer之二维数组中的查找
- 【剑指offer之二维数组中的查找 】
- 剑指offer之二维数组中的查找
- 剑指offer之二维数组中的查找
- 剑指Offer算法实现之三:二维数组中的查找
- 剑指Offer之1384:二维数组中的查找
- 剑指offer面试题3之二维数组中的查找
- 剑指offer系列之1:二维数组中的查找
- 剑指offer(三)之二维数组中的查找
- 剑指offer之面试题3:二维数组中的查找
- [剑指offer学习心得]之:二维数组中的查找
- 剑指Offer之面试题3:二维数组中的查找
- (一)剑指Offer之二维数组中的查找
- 《剑指Offer》面试题三之二维数组中的查找
- 剑指Offer之面试题3:二维数组中的查找
- JS生成渐变颜色
- POI的使用
- 【已解决】Apk签名后报so找不到
- OpenCV 行列值与坐标的对应关系
- java I/O系统(1)-File类
- 【剑指offer之二维数组中的查找 】
- 深入C语言可变参数(va_arg,va_list,va_start,va_end,_INTSIZEOF)
- http状态码清单
- spring4.1.6配置MVC注解
- java 线程池
- 数组指针学习
- C++回炉(4)
- Postgresql GROUPING SETS、CUBE和ROLLUP
- linux epoll详解及使用方法概述