【LintCode】搜索二维矩阵
来源:互联网 发布:nba2k罗德曼数据 编辑:程序博客网 时间:2024/05/17 05:15
描述
写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数。
考虑下列矩阵:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
给出 target = 3
,返回 true
<span style="font-size:18px;">public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix(int[][] matrix, int target) { // write your code here //直接判断 /* if(matrix.length==0) return false; int row=matrix.length; int column=matrix[0].length; int i=0; int j=column-1; while(i<row&&j>=0){ if(target>matrix[i][j]) i++; else if(target<matrix[i][j]) j--; else if(target==matrix[i][j]) return true; } return false;*/ //二分法 int row=matrix.length; if(row==0) return false; int column=matrix[0].length; int len=row*column; int left=0; int right=len-1; //这里的判断条件一定要是left<=right,因为若查找的值在边界的话, //不加=就会停止循环,导致判断不到边界的值 while(left<=right){ int mid=(left+right)/2; int x=mid/column; int y=mid%column; if(target==matrix[x][y]) return true; else if(target>matrix[x][y]) left=mid+1; else if(target<matrix[x][y]) right=mid-1; } return false; }}</span>
0 0
- lintcode ---- 搜索二维矩阵
- lintcode ----搜索二维矩阵
- 【LintCode】搜索二维矩阵
- lintcode,搜索二维矩阵
- LintCode : 搜索二维矩阵
- Lintcode:搜索二维矩阵
- LintCode:搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- 【LintCode】搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- Lintcode 搜索二维矩阵 II
- LintCode 28 搜索二维矩阵
- [LintCode]28.搜索二维矩阵
- lintcode---搜索二维矩阵Ⅱ
- lintcode-搜索二维矩阵II-38
- 搜索二维矩阵——LintCode
- [LintCode]搜索二维矩阵 II
- LintCode 38 搜索二维矩阵 II
- Angular解决IE和Firefox下button内部元素ng-click事件被屏蔽
- JS模拟打字练习
- leetcode——Climbing Stairs
- java如何打印出字符串中的所有数字。
- MySQL 支持 emoji 图标存储
- 【LintCode】搜索二维矩阵
- [JavaAPI]Intellij IDEA生成JavaDoc
- C#试图运行项目时出错 无法启动调试 解决方法!
- AngulaJS自定义指令
- 框架基础--反射机制
- Shell while循环
- php判断上传图片类型是否正确
- EventBus 3.0 使用用例
- 删除数组中重复元素-Hash表方法和set方法