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.

Subscribe to see which companies asked this question

首先二分查找每行的第一个元素,确定了行号后,再在当前行内进行二分查找

值得一提的是其时间复杂度为 O(log(m) + log(n)) = O(log(m*n))

bool searchMatrix(vector<vector<int>>& matrix, int target) {
int beg = , mid, end = matrix.size()-;
while (beg <= end)
{
mid = (beg + end) >> ;
if (target < matrix[mid][])
end = mid - ;
else if (target > matrix[mid][])
beg = mid + ;
else
return true;
}
int row = end;
if (row < )
return false;
beg = ;
end = matrix[row].size();
while (beg <= end)
{
mid = (beg + end) >> ;
if (target < matrix[row][mid])
end = mid - ;
else if (target > matrix[row][mid])
beg = mid + ;
else
return true;
}
return false;
}

最新文章

  1. Mediawiki
  2. Java基础知识学习(五)
  3. viewWithTag获取subview规则详解
  4. vertical-align两种应用场合
  5. Qt 按键长按的处理
  6. 项目视频讲解_[HeyJava][尚学堂][CMS文章内容管理系统]
  7. C# Java间进行RSA加密解密交互(三)
  8. Hibernate一对一单向外键关联
  9. erlang ets表
  10. Modal视图弹出方式
  11. [转]gitlab cicd (二)系列之安装git-runner rpm安装方式
  12. SpringBoot项目打成一个war包
  13. 搭建SDN网络——mininet
  14. bzoj 2434 阿狸的打字机 - Aho-Corasick自动机 - 树状数组
  15. [ActionScript 3.0] 利用InteractivePNG.as类精确选择识别png图片有像素的区域
  16. [freemarker篇]06.超级强大的自定义指令
  17. 2.Access the mongo Shell Help-官方文档摘录
  18. Python 一行代码实现并行
  19. WPF导学目录
  20. linux跨主机复制文件

热门文章

  1. 细数JDK里的设计模式
  2. 必应地图api文档,微软必应地图web开发版详解,可以在国内使用国外地图
  3. nodejs 中使用 mocha + should + jscoverage 生成 单元测试覆盖率报告
  4. java服务器获取客户端ip
  5. linux redis 和 windows redis 的安装
  6. Socket-IOS
  7. 在ubuntu下编写python(python入门)
  8. js立即执行函数: (function ( ){...})( ) 与 (function ( ){...}( ))
  9. C语言 一维数组叠加为二维数组样例
  10. matlab中axis的使用