LeetCode 78 Search a 2D Matrix
来源:互联网 发布:数控开料机用什么软件 编辑:程序博客网 时间:2024/06/05 19:36
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]Given target = 3, return true.
分析:
二分查找,关键在于怎么在二维数组上面进行一维二分查找。
长度为 m*n
mid元素是matrix[mid/n][mid%n]
这样就可以进行二分了。
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { //检查参数 if(matrix==null || matrix.length==0 || matrix[0].length==0) return false; int m = matrix.length; int n = matrix[0].length; //将矩阵转化成一维数组进行二分 int start = 0; int end = m*n-1; while(start <= end){ int mid = (start+end)/2; int val = matrix[mid/n][mid%n];//这行是关键 if(val == target) return true; else if(val < target) start = mid+1; else end = mid-1; } return false; }}
递归风格
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null || matrix.length==0 || matrix[0].length==0) return false; int m = matrix.length; int n= matrix[0].length; return searchMatrix(matrix, target, 0, m*n-1); } public boolean searchMatrix(int[][] matrix, int target, int start, int end){ if(start > end) return false; int mid = (start+end)/2; int x = mid/matrix[0].length; int y = mid%matrix[0].length;//这两行是关键 if(matrix[x][y]==target) return true; if(matrix[x][y] < target) return searchMatrix(matrix, target, mid+1, end); else return searchMatrix(matrix, target, start, mid-1); }}
0 0
- LeetCode 78 Search a 2D Matrix
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- burberry sale NsYX m6fi qSbZn
- C++ Primer 第五版 中文版 练习 13.44 个人code
- cheap louis vuitton fNVZ Owzr 0lS7L
- C++ 链栈
- asp.net控件的异步刷新
- LeetCode 78 Search a 2D Matrix
- Codeforces Round #275 (Div. 2) A
- const 与 static
- 第9周项目6穷举法解决组合问题(1)
- C#设计模式之享元模式(Flyweight Pattern)
- HashCode方法
- Cygwin vim部分颜色配置
- 云计算时代应用设计十二要素
- UnrealEngine3目录