LeetCode - Search a 2D Matrix
2016-01-01 12:53
411 查看
题目:
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:
Given target =
思路:
二分查找
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.
思路:
二分查找
package array; public class SearchA2DMatrix { public boolean searchMatrix(int[][] matrix, int target) { int m; int n; if (matrix == null || (m = matrix.length) == 0 || (n = matrix[0].length) == 0) return false; int start = 0; int end = m * n - 1; while (start <= end) { int mid = (end - start) / 2 + start; int i = mid / n; int j = mid - i * n; if (matrix[i][j] == target) return true; if (matrix[i][j] < target) start = mid + 1; else end = mid - 1; } return false; } 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} }; SearchA2DMatrix s = new SearchA2DMatrix(); System.out.println(s.searchMatrix(matrix, 8)); } }
相关文章推荐
- <LeetCode><Medium>15 ThreeNums
- python类:描述器Descriptors和元类MetaClasses
- MySQL安装详细步骤
- python描述器和元类
- Visual Assist X
- 转帖不会乱码的,powershell网络蜘蛛
- Swift实现OC中的单例模式
- Shell编程进阶 1.2 shell结构及执行
- windows下基于sublime text3的nodejs环境搭建
- 运行XAMPP中的apache出现 Error: Apache shutdown unexpectedly
- 【Linux运维-集群技术进阶】一分钟认识Nginx
- 浅谈顺序表与链表
- (转)应届生经典面试题:说说进程与线程的区别与联系
- 微软雅虎猛追,Google搜索市场份额跌至64%
- 进程管理工具top,htop,glances,dstat的使用
- Xcode的debug和release以及development和distribution证书
- Java 获取请求主机IP地址
- The identity used to sign the executable is no longer valid
- 获取css style值
- poj 1753 Flip Game 高斯消元