240. Search a 2D Matrix II
来源:互联网 发布:怎么删除管家婆数据 编辑:程序博客网 时间:2024/06/03 05:15
240. Search a 2D Matrix II
Write an efficient algorithm that searches for a value in anm xn matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- 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
, returntrue
.
Given target =20
, returnfalse
.
这道题与它的上一题相比不再是前一行的尾元素小于本行的首元素了,所以我想的是首先判断target值是否在所在的行中,如果在则进行二分查找,找到返回true,找不到返回false。如果不在则返回false。最后根据所有返回值的或运算确定最终答案。但是这个方法有个一条件没有用到,就是不及每一行是递增的,每一列也是递增的,这可能导致算法的效率方面的损失。代码如下:
class Solution {public:bool Bsearch(vector<int> row, int low, int high, int target) {while (high >= low){int mid = (low + high) / 2;if (target < row[mid])high = mid - 1;else if (row[mid] < target)low = mid + 1;else return true;}return false;}bool searchMatrix(vector<vector<int>>& matrix, int target) {if (matrix.empty() || matrix[0].empty()) return false;int m = matrix.size();int n = matrix[0].size();bool f = false;for (int i = 0;i < m;i++) {if (target > matrix[i][n - 1] || target < matrix[i][0]) f = f || 0;else f = f || Bsearch(matrix[i], 0, n - 1,target);}return f;}};
看到了大神的思路之后,用到列递增的条件重新编程,效率提高了很多很多(之前平均200ms,改进之后平均60ms):
class Solution {public:bool searchMatrix(vector<vector<int>>& matrix, int target) {if (matrix.empty() || matrix[0].empty()) return false;int m = matrix.size();int n = matrix[0].size();int i = 0, j = n - 1;while (i < m && j >= 0) {if (matrix[i][j] == target)return true;else if (matrix[i][j] > target) j--;else i++;}return false;}};
0 0
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240.Search a 2D Matrix II
- CSDN日报20170421 ——《程序员必知的七个图形工具》
- 多数据库服务器应用实现主从同步从而读写分离
- Wolf从零学编程-用Django撸个Blog(八)服务器部署
- 潜水员
- JavaScript作用域和var的关系
- 240. Search a 2D Matrix II
- ACM 第一天水题
- Sublime Text3 + Golang搭建开发环境
- 递归算法
- 三线城市创业之路-办公室的选择和服务质量的竞争力
- 朱刘算法模板(最小树形图)
- 通过mybatis批量获取oracle序列号的方法
- 快速排序
- JaveSE聊天案例