文章标题
来源:互联网 发布:淘宝看在线人数的插件 编辑:程序博客网 时间:2024/05/22 02:29
240/Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
1)Integers in each row are sorted in ascending from left to right.
2)Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
题意:
编写一个高效的算法,查询m*n矩阵中的某个值。这个矩阵具有以下属性:
1.每一行的整数从左到右按升序排序。
2.每一列的整数从上到下按升序排序。
解题思路:二分法
先二分查找第一列,找出目标值所在的行,再对所在行进行二分查找!
代码:
class solution{public: bool searchMattrix(vector<vector<int>>&matrix,int target) { int m = matrix.size();//行数 int n = matrix[0].size();//列数 int index=binary_search_1(matrix,target,0,m-1);//对第一列进行二分查找,锁定所在行 if(index<0 || index>=m) return false; return binary_search_2(matrix[index],target,0,n-1);//对所在行进行二分查找 }protected: int binary_search_1(vector<vector<int>> &matrix, int target, int start, int end) //先锁定target所在行 { if(start >= end) return start; int mid = (start + end)/2; if(target >= matrix[mid][0] && target < matrix[mid+1][0]) return mid; else if(target < matrix[mid][0]) { return binary_search_1(matrix,target,start,mid-1); } else { return binary_search_1(matrix,target,mid+1,end); } } bool binary_search_2(vector<int> &row, int target, int start, int end) //在锁定行中查找target { if(start>=end) return row[start]==target; int mid=(start+end)/2; if(row[mid]==target) return true; else if(row[mid]<target) return binary_search_2(row,target,mid+1,end); else return binary_search_2(row,target,start,mid-1); }};
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 运动会分数统计系统开发(第一版)
- 一、git基本常用操作
- C库函数 - fseek()
- 时间与果实
- FLV科普7 FLV时间戳计算
- 文章标题
- JAVA-中介者设计模式
- 《开源安全运维平台:OSSIM最佳实践》内容简介
- c#界面开发自定义快捷键
- IOS UITextField常用的代理方法总结
- android 界面中的各种布局
- 修改Eclipse 45秒超时
- 状态机设定与编码选择
- 新打开acitivyt时,EditText焦点自动带出软键盘问题解决方法总结 ... ...