搜索二维矩阵 II
来源:互联网 发布:竞翔通软件 编辑:程序博客网 时间:2024/06/05 22:51
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每一列的整数从上到下是排序的。
- 在每一行或每一列中没有重复的整数。
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
解题思路:递增数组,思路为从左下或者右上开始查找。
此题,我从左下开始查找,第一个为3,num++,然后向上移动一行,去掉第三行,
到2,发现比target小,右移一行,去掉第一列。依次移动。
public class Solution { /** * @param matrix: A list of lists of integers * @param: A number you want to search in the matrix * @return: An integer indicate the occurrence of target in the given matrix */ public int searchMatrix(int[][] matrix, int target) { // write your code here if(matrix==null||matrix.length==0){ return 0; } else if(matrix[0]==null||matrix[0].length==0){ return 0; } int row=matrix.length-1; int col=matrix[0].length-1; int r=row; int c=0; int num=0; while(r>=0&&c<=col){ if(matrix[r][c]==target){ num++; r--; } else if(matrix[r][c]>target){ r--; } else if(matrix[r][c]<target){ c++; } } return num; }}
阅读全文
1 0
- 搜索二维矩阵 II
- 搜索二维矩阵 II
- 搜索二维矩阵 II
- 搜索二维矩阵II
- 搜索二维矩阵 II
- 搜索二维矩阵II
- 搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- 【LintCode】搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- Lintcode 搜索二维矩阵 II
- lintcode-搜索二维矩阵II-38
- [LintCode]搜索二维矩阵 II
- LintCode 38 搜索二维矩阵 II
- Java实现-搜索二维矩阵II
- [LintCode]38.搜索二维矩阵 II
- Google/LintCode:M-搜索二维矩阵 II
- recyclerView之软引用
- JSON.parseObject报错
- java反射机制
- Vue2.0组件实现动态搜索引擎(一)
- java数据结构与算法之顺序表与链表深入分析
- 搜索二维矩阵 II
- plsql创建表
- C++内存泄露的检测识别方法
- 自己实现strstr函数与strchr函数
- python 读取 csv 中文 乱码 解决办法
- 单元测试入门
- Lua程序设计2 笔记
- 在Linux安装配置Tomcat 并部署web应用 ( 三种方式 )
- 友元函数 friend