search-a-2d-matrix
2016-06-10 23:02
239 查看
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.
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.
//从左下角开始查找 class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int m=matrix.size(),n=matrix[0].size(); if(m==0||n==0) return false; if(matrix[0][0]>target||matrix[m-1][n-1]<target) return false; int i=m-1,j=0; while(i>=0&&j<n){ if(target==matrix[i][j]){ return true; } else if(target<matrix[i][j]){ i--; } else{ j++; } } return false; } }; //正版二分法 class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int m=matrix.size(),n=matrix[0].size(); if(m==0||n==0) return false; if(matrix[0][0]>target||matrix[m-1][n-1]<target) return false; int left=0,right=m*n-1,mid; while(left<=right){ mid=left+(right-left)/2; if(target==matrix[mid/n][mid%n]){ return true; } else if(target<matrix[mid/n][mid%n]){ right--; } else{ left++; } } return false; } };
相关文章推荐
- NFS服务器配置
- JavaSE复习_3 继承
- java8十大新特性浅谈
- CSS学习记录——表格
- Exception in thread "main" java.lang.RuntimeException: job failed: name=inject urls, jobid=job_local
- 获取当前日期时间、日期时间格式化及转换
- 重装64位系统
- 专2-第二课 Eclipse开发环境搭建
- 第四百三十四天 how can I 坚持
- Android Touch事件传递机制
- BZOJ_1613_ [Usaco2007_Jan]_Running_贝茜的晨练计划_(动态规划)
- openSUSE 安装oracle jdk
- 元素淡入淡出效果
- 数据库优化概览
- 网页刷新页面方法小结
- Spring创建对象的方式3种方式
- Caused by: org.xml.sax.SAXParseException; systemId: file:/opt/apache-nutch-2.2.1/runtime/local/conf/
- 关于mysql的索引
- 一个 fork 的面试题
- 构建之法阅读笔记05