74. Search a 2D Matrix
2016-02-19 21:51
447 查看
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.
解析
根据题意,如果把二维数组拉直,看成一列的话,很明显这是一个递增的数列。则很容易想到二分查找法。同时,根据某个值所在的序号(index),易计算其所在行和列。
行号=index/collength;
列号=index%collength;
代码
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { //二分查找 int left=0; int right = matrixRowSize*matrixColSize-1; while(left<=right){ int mid = (left+right)/2; int row = mid/matrixColSize; int col = mid%matrixColSize; if(matrix[row][col]==target){ return true; } else if(matrix[row][col]>target){ right=mid-1; } else{ left=mid+1; } } return false; }
时间复杂度为:O(log(m+n))
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Linux C函数参考手册(PDF版)
- Lua中调用C++函数示例
- Lua教程(十七):C API简介
- 简单谈谈lua和c的交互
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C#实现打造气泡屏幕保护效果
- 举例讲解C#编程中委托的实例化使用
- 使用C#代码获取存储过程返回值
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析