LintCode:搜索二维矩阵 II
2015-11-05 09:32
423 查看
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
您在真实的面试中是否遇到过这个题?
Yes
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
标签 Expand
相关题目 Expand
解题思路:
从左下脚开始搜索即可
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
您在真实的面试中是否遇到过这个题?
Yes
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
标签 Expand
相关题目 Expand
解题思路:
从左下脚开始搜索即可
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 res = 0; if (null == matrix || 0 == matrix.length) return res; int row = matrix.length; int colum = matrix[0].length; int i = row - 1; int j = 0; while (i >= 0 && j < colum) { if (target == matrix[i][j]) { res++; i--; j++; } else if (target > matrix[i][j]) { j++; } else { i--; } } return res; } }
相关文章推荐
- 显示网络上的图片
- Word撤销键(Ctrl+z)无效的解决方法
- openwrt-智能路由器hack技术(2)---"网路信息监控和窃取"
- Linux之命令的组合
- Linux之命令的组合
- 这样的简历,到哪里都是被淘汰的命!
- PHP中双冒号::的用法
- LintCode:搜索旋转排序数组
- 检查网络状态信息的API
- Git两分钟指南-学习入门参考
- 2015 北京网络赛 C Protecting Homeless Cats hihoCoder 1229 树状数组
- LintCode:接雨水
- LintCode:排颜色 II
- 如何用Swift实现一个好玩的弹性动画
- 【洛谷T577】【模板】template 最短路 SPFA+dij
- asp.net <%%> <%#%><%=%><%@%><%$%>用法区别
- Quartz.net开源作业调度框架使用详解
- Source Insight基本使用和快捷键
- jmeter入门指南
- 常用的正则表达式总结