LeetCode3 Search a 2D Matrix
来源:互联网 发布:python 数据库框架 编辑:程序博客网 时间:2024/04/30 11:56
LeetCode3 Search a 2D Matrix
1、题目描述
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
2,解题思路
首先将特定的二维矩阵转化为按大小排列的一位数组
利用二分法搜索目标值
3、实现代码
#include<iostream>using namespace std;int main (){ cout<<"please input the size of the m x n matrix"<<endl; int m,n; cin>>m>>n; int mn=m*n; int mat[m][n],mat1[mn]; int k=0; cout<<"please input elements of the matrix: "<<endl; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ cin>>mat[i][j]; mat1[k]=mat[i][j]; k++; } } cout<<"please input the search number: "; int dest; cin>>dest; int indb=0,inde=mn-1; int b=mat1[indb],e=mat1[inde]; int ind=mn/2,med=mat1[ind]; bool ans=0; if( (b<=dest) && (dest<=e) ){ if((dest==b)||(dest==e)) ans=1; else{ while(inde-indb>1){ if(dest==med){ ans=1; break; } else{ if(dest<med){ e=med; inde=ind; ind=(indb+inde)/2; med=mat1[ind]; } else{ b=med; indb=ind; ind=(indb+inde)/2; med=mat1[ind]; } } } if((dest==b)||(dest==e)){ ans=1; } } } if(ans) cout<<"ture"<<endl; else cout<<"false"<<endl; return 0;}
4、实验结果
0 0
- LeetCode3 Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D matrix
- C++从.c到.out
- Divisible by Seven
- 网易MySQL数据库工程师微专业学习笔记(十)
- Xcode启动失败,提示"Loading a plug-in failed The plug-in or one of its prerequisite plug-ins may be missin
- java提高篇(十三)-----字符串
- LeetCode3 Search a 2D Matrix
- idea
- java使用redis
- Python3.6 zip lambda
- (蓝桥杯第六届B组)加法变乘法
- 无法解析或打开软件包的列表或是状态文件
- 左偏树
- 关于首屏性能优化的总结【原创】
- 关于android studio 出现Error:Execution failed for task ':app:buildInfoDebugLoader'.的解决办法