74. Search a 2D Matrix
来源:互联网 发布:淘宝打印助手怎么样 编辑:程序博客网 时间:2024/04/28 13:31
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
.
题意:给定一个二维数组,每一行从左到右递增,每一行的第一个元素比上一行最后一个元素大,求给定的target是否存在数组中。
仔细观察一下就能相到:虽然题目给定的是一个二维数组,但是实际上我们可以等价于一个升序排序的一维数组,这样一来使用二分查找就可以很容易解决此题;
代码:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 || matrix[0].length == 0) return false; int rowlen = matrix.length; int collen = matrix[0].length; int start = 0; int end = rowlen*collen-1; while(start <= end){ int mid = (start+end)/2; int midr = mid/collen; int midc = mid%collen; if(target == matrix[midr][midc]) return true; if(target < matrix[midr][midc] ) end = mid-1; else start = mid+1; } return false; }}
阅读全文
0 0
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- 从超级菜鸟变成Linux系统高手
- FFmpeg使用手册
- 在Hibernate中开启日志
- 为什么本地开发时使用CURL请求本地URL会卡死
- Hadoop NameNode 高可用 (High Availability) 实现解析
- 74. Search a 2D Matrix
- c#
- 微信推送
- Android studio使用ndk-build进行编译
- thinkphp3.2.3整合workerman
- JNI调用java层的方法
- hdu2627Life(水题)
- Android动态代理实践之Hook系统剪切板服务
- OTA升级Google官方文档翻译——OTA 软件包内部