leetcode oj java Search a 2D Matrix
来源:互联网 发布:达内java就业 编辑:程序博客网 时间:2024/06/07 00:07
一、问题描述:
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,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3
, return true
.
二、解决方案:
矩阵行扫描是有序的,用典型的二分查找。矩阵为m*n, 看为一个1 * (m*N)的数组,第k个位置对应到矩阵的[k/n][k%n]
三、代码:
package T12;/** * @author 作者 : xcy * @version 创建时间:2016年12月22日 下午11:48:33 * 类说明 */public class t74 { public static void main(String[] args) { // TODO Auto-generated method stub int[][] matrix = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } }; int target = 51; System.out.println(searchMatrix(matrix, target)); } public static boolean searchMatrix(int[][] matrix, int target) { boolean flag = false; int m = matrix.length; if(m==0){ return false; } int n = matrix[0].length; int num = m * n; int start = 0; int end = num; int x = 0; int y = 0; int mid = 0; while (start < end) { mid = (start + end) / 2; x = mid / n; y = mid % n; if (target == matrix[x][y]) { return true; } if (target < matrix[x][y]) { end = start + (end - start) / 2; } if (target > matrix[x][y]) { start = end - (end - start) / 2; } } return flag; }}
0 0
- leetcode oj java Search a 2D Matrix
- leetcode oj java Search a 2D Matrix II
- LeetCode OJ:Search a 2D Matrix
- LeetCode OJ - Search a 2D Matrix
- [LeetCode OJ]Search a 2D Matrix
- LeetCode OJ Search a 2D Matrix
- LeetCode OJ | Search a 2D Matrix
- [Leetcode] Search a 2D Matrix (Java)
- [LeetCode][Java] Search a 2D Matrix
- leetcode:Search a 2D Matrix 【Java】
- Search a 2D Matrix leetcode java
- LeetCode OJ-74.Search a 2D Matrix
- LeetCode OJ 240. Search a 2D Matrix II
- [leetcode][Search] Search a 2D Matrix
- LeetCode – Search a 2D Matrix (Java)
- 【Leetcode】Search a 2D Matrix in JAVA
- LeetCode(074) Search a 2D Matrix (Java)
- leetcode 240 Search a 2D Matrix II java 算法
- 侧滑面板
- 滚动视图上滑动改变导航条颜色和透明度
- Java KMP匹配算法的实现
- 我的世界 unity3d minecraft 用unity3d来制作类似我的世界的游戏 优化树和草
- 50. Pow(x, n)
- leetcode oj java Search a 2D Matrix
- 05-JS特效-缓动动画
- LeetCode解题报告 445. Add Two Numbers II [medium]
- 数据结构 指针知识
- Objective-C中的@property
- H5项目常见问题及注意事项[连载中]
- SP存储
- 强大而流行的C语言
- java.class.getClassLoader 容易理解的方式