一、问题描述
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所在的行,再确定target所在列,因为行列均为有序的,所以可以采用两次二分查找;其二,将整个矩阵看成是一个一维数组,长度为row*column,只不过在确定mid的时候需要转换成行和列。
三、Java AC 代码
方法一
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
if (target < matrix[0][0]
|| target > matrix[matrix.length - 1][matrix[0].length - 1]) {
return false;
}
int low = 0;
int high = matrix.length - 1;
int mid = 0;
int row = -1;
while (low <= high) {
mid = (low + high) / 2;
if (target == matrix[mid][0]) {
return true;
} else {
if (target > matrix[mid][0]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
row = high;
low = 0;
high = matrix[0].length - 1;
mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (target == matrix[row][mid]) {
return true;
} else {
if (target > matrix[row][mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return false;
}
方法二
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0||matrix[0].length==0||matrix==null)
return false;
int rows = matrix.length;
int cols = matrix[0].length;
int low = 0;
int high = rows*cols-1;
while(low<=high){
int mid = (low+high)/2;
int midValue = matrix[mid/cols][mid%cols];
if(midValue == target)
return true;
else if(midValue < target)
low = mid+1;
else
high = mid-1;
}
return false;
}