编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

方法一:使用二分查找
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int[] row : matrix){ //按行查找
int index = search(row,target);
if(index >= 0){
return true;
}
}
return false;
}
//使用二分查找
public int search(int[] nums,int target){
int low = 0,high = nums.length -1;
while(low <= high){
int mid = (high - low) / 2 + low;
int num = nums[mid];
if(num == target){
return mid;
}else if(num > target){
high = mid -1;
}else{
low = mid + 1;
}
}
return -1;
}
}
方法二:Z字形查找
从矩阵的右上角(0,n-1)进行搜索,在每一步的搜索过程中,如果我们位于位置(x,y),那么就希望在矩阵的左下角为左下角,以(x,y)为右上角的矩阵中进行搜索,即行的范围为[x,m-1],列的范围为[0,y]
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length,n = matrix[0].length;
int x = 0,y = n-1;
while(x < m && y >= 0){
if(matrix[x][y] == target){
return true;
}
if(matrix[x][y] > target){
--y;
}else{
++x;
}
}
return false;
}
}