Search a 2D Matrix leetcode
2024-10-05 10:14:45
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;
}
最新文章
- Mediawiki
- Java基础知识学习(五)
- viewWithTag获取subview规则详解
- vertical-align两种应用场合
- Qt 按键长按的处理
- 项目视频讲解_[HeyJava][尚学堂][CMS文章内容管理系统]
- C# Java间进行RSA加密解密交互(三)
- Hibernate一对一单向外键关联
- erlang ets表
- Modal视图弹出方式
- [转]gitlab cicd (二)系列之安装git-runner rpm安装方式
- SpringBoot项目打成一个war包
- 搭建SDN网络——mininet
- bzoj 2434 阿狸的打字机 - Aho-Corasick自动机 - 树状数组
- [ActionScript 3.0] 利用InteractivePNG.as类精确选择识别png图片有像素的区域
- [freemarker篇]06.超级强大的自定义指令
- 2.Access the mongo Shell Help-官方文档摘录
- Python 一行代码实现并行
- WPF导学目录
- linux跨主机复制文件
热门文章
- 细数JDK里的设计模式
- 必应地图api文档,微软必应地图web开发版详解,可以在国内使用国外地图
- nodejs 中使用 mocha + should + jscoverage 生成 单元测试覆盖率报告
- java服务器获取客户端ip
- linux redis 和 windows redis 的安装
- Socket-IOS
- 在ubuntu下编写python(python入门)
- js立即执行函数: (function ( ){...})( ) 与 (function ( ){...}( ))
- C语言 一维数组叠加为二维数组样例
- matlab中axis的使用