74. Search a 2D Matrix
2016-04-19 16:29
274 查看
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 =
思路:就是两次二分查找的过程,第一次二分查找确定在哪一行,第二次二分查找确定有没有
代码如下(已通过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);
}
}
}
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);
}
}
}
相关文章推荐
- spring bean的scope属性
- fzu2226
- 取消低版本自定义对话框的背景
- HM编码器代码阅读(18)——变换以及量化(一)
- Hibernate查询对象所有字段,单个字段 ,几个字段取值
- Python 解析配置模块之ConfigParser详解
- <<程序员面试宝典>>读书笔记 2
- 工作中需要了解的内容备份,将来有时间学习
- HashMap实现原理
- 软件设计模式:享元模式(Flyweight)
- 分布式处理 幂等设计
- 安卓跑马灯的实现
- 2016年最新苹果开发者账号注册申请流程最强详解!
- 【转】如何用 C/C++ 求 1 到 1000 内的所有完全数
- SVN查找某个作者的
- 学习软件工程有感
- RxJava 操作符之创建类操作符
- 自定义listview/gridview实现在scrollview中滑动
- 在Windows服务器上启用TLS 1.2及TLS 1.2基本原理
- js 中用 location.pathname 获取项目名