74. Search a 2D Matrix
来源:互联网 发布:python换两行 编辑:程序博客网 时间:2024/06/08 01:55
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
.
思路:就是两次二分查找的过程,第一次二分查找确定在哪一行,第二次二分查找确定有没有
代码如下(已通过leetcode)
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row=findrow(matrix, target, 0, matrix.length-1);
//System.out.println("第"+row+"行");
if(findit(matrix, row, target, 0, matrix[row].length-1)==Integer.MIN_VALUE) return false;
else {
//int position=findit(matrix, row, target, 0, matrix[row].length-1);
//System.out.println("第"+row+"行"+"第"+position+"位");
return true;
}
}
public int findrow(int[][] matrix,int target,int low,int high) {
while(low<=high) {
if(matrix[low][matrix[low].length-1]<target) low++;
else {
return low;
}
}
return low-1;
}
public int findit(int[][] matrix,int row,int target,int low,int high) {
if(low>high) return Integer.MIN_VALUE;
int mid=(low+high)/2;
if(matrix[row][mid]==target) return mid;
else {
if(matrix[row][mid]>target){
high=mid-1;
} else {
low=mid+1;
}
return findit(matrix, row, target, low, high);
}
}
}
- 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
- 安卓跑马灯的实现
- 2016年最新苹果开发者账号注册申请流程最强详解!
- [编程题]路灯
- 【转】如何用 C/C++ 求 1 到 1000 内的所有完全数
- 工作中需要了解的内容备份,将来有时间学习
- 74. Search a 2D Matrix
- Sublime Text在Windows/Ubuntu/Mac OSX中配置使用CTags
- fzu2226
- 异步传输字符串
- 安卓seekBar的使用(初学者)
- 关于getElementsByName("")的使用
- 欢迎使用CSDN-markdown编辑器
- 5个数组Array方法: indexOf、filter、forEach、map、reduce使用实例
- 输出日志查看数据