Search a 2D Matrix
Description
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.
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
Challenge
O(log(n) + log(m)) time
实现思路
总体查找思路是基于2分法,先根据每行第一列元素进行2分,找出元素具体所在行,再对该行进行2分,查找该元素
1. 开始注意检查矩阵长度为0的边界条件
2. 具体实现思路是计算中间行,判断元素是否在中间行里(大于行首小于行尾),否则判断是否大于行首,来确定所查找元素应该实在行内,还是小于当前行或大于当前行。
3. 找到行后,退化到简单的一维数组二分。
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
int lenrow = matrix.length;
if(lenrow == 0){
return false;
}
int lencol = matrix[0].length;
if(lencol == 0){
return false;
}
int lrow = 0,rrow = lenrow -1;
int midrow = 0;
while(lrow <= rrow){
midrow = (rrow - lrow ) / 2 + lrow;
if(matrix[midrow][0] <= target && matrix[midrow][lencol-1] >= target){//
break;
}else if(matrix[midrow][0] > target){
rrow = midrow -1;
}else{
lrow = midrow + 1;
}
}
int lcol = 0,rcol = lencol - 1;
int midcol = 0;
while(lcol <= rcol){
midcol = (rcol - lcol ) / 2 + lcol;
if(matrix[midrow][midcol] == target){
return true;
}else if(matrix[midrow][midcol] > target){
rcol = midcol -1;
}else{
lcol = midcol + 1;
}
}
return false;
}