//FindInPartiallySortedMatrix
//题目意思是 给一个矩阵 这个矩阵的每一行都是有序 递增的
//并且每一列都是有序 递增的 要在这个矩阵中查找一个值
//分析思路 如果随机选一个数比要找的小 那肯定是在右方或下方。这样不方便。还有重叠区域
//就应该找特殊点 比如上下左右 四个点 左上一直是最小 没什么价值 右下一直是最大。。
//现在想右上 的数它是一行中最大的 一列中最小的 也就是说 如果要查找的数比它小 肯定不在那一列 比他大 肯定不再那行
//这样我们每次都可以排除一行 或者一列。直到只剩下一个元素 不相等的话 就没找到。
//时间复杂度是O(n+m)
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100;
int arr[maxn][maxn],n,m;
void init()
{
scanf("%d %d",&n,&m);
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
scanf("%d",&arr[i][j]);
}
void showarr()
{
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
cout<<arr[i][j]<<" ";
cout<<endl;
}
}
bool Find(int a)//标记xpos ypos 为要查找区域的右上角。
{
int xpos = 0;//初始化未右上角 一开始写错 写成右下角了
int ypos = m-1;
while(xpos<n && ypos>=0)//x是在向下 增大 y是在向左 减小
{
if(a==arr[xpos][ypos])
return true;
else if(a<arr[xpos][ypos])
ypos--;
else
xpos++;
}
return false;
}
int main()
{
freopen("/home/gl/in","r",stdin);
init();
showarr();
int num;
while(scanf("%d",&num)!=EOF)
{
printf("searching %d ",num);
if(Find(num))
printf("Find\n");
else
printf("Not find\n");
}
return 0;
}
剑指offer面试题3 在一个每一行递增 且每一列递增的二维数组中查找一个数
最新推荐文章于 2021-05-26 04:00:22 发布