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
.
在一个有序的二维数组里面查找一个值,思路是先对行二分查找,再对这行二分查找,不过我的代码只二分查找了行,遍历了这一行也能AC。。
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0||matrix[0].length==0)return false;
int row = matrix.length-1;
int col = matrix[0].length-1;
int l = 0;
int r = row;
int m = (l+r)/2;
int c = 0;
while(l<=r){
if(matrix[m][0]>target&&m!=0&&matrix[m-1][0]<=target){
c = m-1;
break;
}
if(matrix[m][col]<target&&m!=row&&matrix[m+1][col]>=target){
c = m+1;
break;
}
if(matrix[m][0]>target){
r = m-1;
m = (l+r)/2;
}
else{
l = m+1;
m = (l+r)/2;
}
}
for(int i=0;i<=col;i++){
if(matrix[c][i]==target)return true;
}
return false;
}
}