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.
[code]
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null || matrix.length==0 || matrix[0].length==0)return false;
int start=0, end=matrix.length*matrix[0].length-1,mid;
while(start<=end)
{
mid=(start+end)/2;
int r[]=getPosition(matrix,mid);
int middle=matrix[r[0]][r[1]];
if(middle==target)return true;
else if(middle<target)start=mid+1;
else end=mid-1;
}
return false;
}
int [] getPosition(int[][]matrix, int index)
{
int r[]=new int[2];
int m=matrix.length, n=matrix[0].length;
r[0]=index/n;
r[1]=index%n;
return r;
}
}
[Thoughts]
矩阵index容易错,用简单矩阵验证一下like
0 1 2
3 4 5
6 7 8