Search a 2D Matrix
来源:互联网 发布:linux系统查看cpu主频 编辑:程序博客网 时间:2024/06/03 09:15
Search a 2D Matrix
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
.
解题技巧:
先用二分搜索法找到目标所在的行,再用二分搜索法得到目标所在的列。如果找到目标,则返回true;否则,返回false。时间复杂度为o(logm+logn)
代码:
bool searchMatrix(vector< vector<int> >& matrix, int target){ int bg1, ed1, mid1, bg2, ed2, mid2; if(matrix.size() == 0) return false; bg1 = 0, ed1 = matrix.size(); //行 bg2 = 0, ed2 = matrix[0].size(); //列 while(bg1 <= ed1) { mid1 = (bg1 + ed1)/2; if(matrix[mid1][0] == target) return true; else if(matrix[mid1][0] > target) ed1 = mid1 - 1; else if(matrix[mid1][0] < target) { if(mid1 + 1 >= matrix.size()) break; else { if(target < matrix[mid1+1][0]) break; else bg1 = mid1 + 1; } } } while(bg2 <= ed2) { mid2 = (bg2 + ed2)/2; if(matrix[mid1][mid2] == target) return true; else if(matrix[mid1][mid2] > target) ed2 = mid2 - 1; else bg2 = mid2 + 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
- android中手动切换app语言
- 【OpenGL】对像素图像的一些操作
- 关于导航栏背景图要注意的一点
- Python标准模块——os
- Python3中获取文件夹内容的几种方式
- Search a 2D Matrix
- 用Shader绘制自由多边形
- BZOJ1588: [HNOI2002]营业额统计
- 快速排序
- Python标准模块——glob
- Android内存溢出与优化(一)——不要随意new对象
- 基于visual studio 2015的Qt平台搭建方案
- <Principles of fMRI 1>课程笔记4--图像K空间理解
- AngularJS ui-router (嵌套路由)