搜索二维矩阵 II
来源:互联网 发布:mac添加dock 编辑:程序博客网 时间:2024/05/17 06:08
搜索二维矩阵 II
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每一列的整数从上到下是排序的。
- 在每一行或每一列中没有重复的整数。
样例考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
思路:行和列都是有序的,如果以右上角为起点来判断大小,矩阵是不断缩小的
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每一列的整数从上到下是排序的。
- 在每一行或每一列中没有重复的整数。
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
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 int rowLen = matrix.length-1; if(rowLen<0){ return 0; } int colLen = matrix[0].length-1; int i = 0; int j = colLen; int count = 0; while(i<=rowLen && j >= 0){ if(matrix[i][j] > target){ j--; } else{ if(matrix[i][j] == target){ count++; i++; j--; } else{ i++; } } } return count; }}
0 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
- 新建javaweb项目环境准备
- 不要使用TRANSIENT的常规方式来缓存WP_QUERY
- git学习笔记
- PAT A1030 Travel Plan(30)
- android-Animation动画效果
- 搜索二维矩阵 II
- 学习12864 5*8
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 自述创业史 - XMove动作感应系统(二)
- Python简介
- Centos6中Python2.6升级2.7
- HDU Coins(dp)
- linux进入退出命令界面
- 大神博客地址