No
推荐指数:※
来源:http://ac.jobdu.com/problem.php?pid=1384
这也是海涛的剑指offer上的题目。把cin改成scanf吧。
第一次想到的解法:(其实在寻找行列上也可以使用二分查找)
#include<iostream> #include<string.h> #include<stdio.h> #include<stdlib.h> using namespace std; int b_find(int *arr,int val,int length){ int low=0,high=length-1; while(low<=high){ int mid=(low+high)/2; if(arr[mid]==val) return mid; else if(arr[mid]>val) high=mid-1; else low=mid+1; } return -1; } int main() { int m,n; while(cin>>m>>n){ int val; cin>>val; int **arr,i,j; arr=new int *[m]; for(i=0;i<m;i++){ arr[i]=new int [n]; for(j=0;j<n;j++) scanf("%d",&arr[i][j]); } int flag=false; int low=-1,high=-1; for(i=0;i<m;i++) if(arr[i][n-1]>=val){ low=i; break; } for(i=m-1;i>=0;i--) if(arr[i][0]<=val){ high=i; break; } if(low!=-1&&high!=-1&&low<=high){ for(i=low;i<=high;i++){ if(b_find(arr[i],val,n)!=-1){ flag=true; break; } } } if(flag==true) printf("Yes\n"); else printf("No\n"); } return 0; }
#include<iostream> #include<string> #include<stdio.h> #include<stdlib.h> using namespace std; int main() { int m,n; while(scanf("%d%d",&m,&n)!=EOF){ int **arr,i,j,val; arr=new int*[m]; cin>>val; for(i=0;i<m;i++){ arr[i]=new int [n]; for(j=0;j<n;j++) scanf("%d",&arr[i][j]); } int p=0,q=n-1; bool flag=false; while(p<m&&q>=0){ if(arr[p][q]==val){ flag=true; break; } else if(arr[p][q]<val) p++; else q--; } if(flag==true) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }