[LintCode]38.搜索二维矩阵 II
来源:互联网 发布:网络职业男士头像大全 编辑:程序博客网 时间:2024/05/29 15:14
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:每行中的整数从左到右是排序的。每一列的整数从上到下是排序的。在每一行或每一列中没有重复的整数。
样例:考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
思路:从左下角或右上角开始搜索均可,每次判断大小换行或者换列移动。比较matrix[row][col]与target的关系。
class Solution {public: /** * @param matrix: A list of lists of integers * @param target: An integer you want to search in matrix * @return: An integer indicate the total occurrence of target in the given matrix */ int searchMatrix(vector<vector<int> > &matrix, int target) { if(matrix.empty() || matrix[0].empty()) { return 0; } int row=0; int col=matrix[0].size()-1; int count=0; while(row<matrix.size() && col>-1){ if(matrix[row][col]==target){ count++; col--; // row++; //加上这两行,避免死循环 }else if(matrix[row][col] > target){ col--; }else{ row++; } } return count; }};
阅读全文
0 0
- [LintCode]38.搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- 【LintCode】搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- Lintcode 搜索二维矩阵 II
- lintcode-搜索二维矩阵II-38
- [LintCode]搜索二维矩阵 II
- LintCode 38 搜索二维矩阵 II
- Google/LintCode:M-搜索二维矩阵 II
- LintCode之38 搜索二维矩阵 II
- lintcode ---- 搜索二维矩阵
- lintcode ----搜索二维矩阵
- 【LintCode】搜索二维矩阵
- lintcode,搜索二维矩阵
- LintCode : 搜索二维矩阵
- Lintcode:搜索二维矩阵
- 搜索二维矩阵 II
- JAVA设计模式之单例模式
- 算法题练习系列之(二十一): 人口普查
- 将输入的数以任意进制(16进制以内)输出
- 1.20.ARM汇编指令集8之存储器访问指令(LDM和STM & SWP)
- bootstrap系列之三列表与代码样式
- [LintCode]38.搜索二维矩阵 II
- 使用Spring Boot搭建个人博客全记录
- C++ 容器的概念
- BFC
- HTML&CSS初级
- Springboot搭建web项目访问自定义位置的html页面
- FTP部署
- JavaScript 对象_0
- Spring cloud 学习(二)Feign