Search a 2D Matrix
来源:互联网 发布:碧海潮生曲 知乎 编辑:程序博客网 时间:2024/05/18 17:03
原题如下:
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.
这个题其实还是很简单的,直接暴力也能AC, C++代码如下:
bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.size() < 1 || matrix[0].size() < 1) return false; int m = matrix.size(), n = matrix[0].size(); for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(matrix[i][j] == target){ return true; } } } return false; }
不过既然有规律可循,那肯定要找到一种高效的方法了,可以考虑把矩阵“展平”,这不就是二分查找嘛。这样一下子就可以把时间从O(MN)降到了O(Log(MN))了。AC过的C++代码如下:
bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.size() < 1 || matrix[0].size() < 1) return false; int m = matrix.size(), n = matrix[0].size(); int left = 0, right = m * n - 1; while(left <= right){ int mid = (left + right) / 2; int i = mid /n, j = mid % n; if(matrix[i][j] == target) return true; else if(matrix[i][j] > target){ right = mid - 1; }else{ left = mid + 1; } } return false; }
0 0
- 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
- Java栈与堆
- php设计模式之原型模式
- Python条件语句
- QT creator+OpenCV2.4.2+MinGW 在windows下开发环境配置
- 使用.NET Reflector 查看Unity引擎里面的DLL文件
- Search a 2D Matrix
- PHP 数组运算符
- (二)设计模式之UML六大关系
- 实现和IE浏览器交互的几种方法的介绍(二)
- 修改npm包管理器的registry为淘宝镜像(npm.taobao.org)
- 如何在120行内实现一个有协程并支持tbus的服务器框架
- 单源最短路径--Dijkstra
- DragGridView使用
- 初识ps君记录~~