Search a 2D Matrix
2015-07-25 15:50
225 查看
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:
Given target =
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.
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int sizeX = (int)matrix.size(); if (0 == sizeX) { return false; } int sizeY = (int)matrix[0].size(); return searchMatrix(matrix, target, 0, 0, sizeX - 1, sizeY - 1); } private: bool searchMatrix(vector<vector<int> > &matrix, int target, int begX, int begY, int endX, int endY) { if (begX > endX || begY > endY) { return false; } int midX = (begX + endX) >> 1; int midY = (begY + endY) >> 1; vector<int> const & tmp = matrix[midX]; int val = tmp[midY]; if (val == target) { return true; } if (target > val) { if (target > tmp[endY]) { return searchMatrix(matrix, target, midX + 1, begY, endX, endY); } return binary_search(&tmp[midY], &tmp[endY] + 1, target); } if (target < tmp[begY]) { return searchMatrix(matrix, target, begX, begY, midX - 1, endY); } return binary_search(&tmp[begY], &tmp[midY], target); } };
相关文章推荐
- 输入一
- git - 远程分支
- HDU 4628 Pieces (状压DP)
- to_char()函数返回日期格式为年月日时分秒格式
- XML解析(二) SAX解析
- redo日志的理解
- cocos2d-xUI编译器导出的json,程序中怎么读取?遇到自定义字体UILabelBMFont,怎么在程序中修改他的值?怎么将json再次导入编译器中?
- JavaScript类继承及实例化的方法
- Snail—OC学习之日期NSDate
- 安卓检测wifi网络状态以及强度,及检测电量。
- NYOJ 739 笨蛋难题四
- Code Forces 377 A. Maze(dfs)
- Struts2自定义Result处理JSON
- XML解析(一) DOM解析
- 一个HashMap和TreeSet综合使用的小例子
- Linux 下stat和access函数
- POJ 2823单调队列 数组写法
- JavaStuNote 6
- 浅析函数调用栈
- hdoj 1241 Oil Deposits (dfs)