(1)二分法
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;
int end =(matrix.length)*(matrix[0].length)-1;
while(start<=end)
{
int mid=(end+start)/2;
int rol=mid/matrix[0].length;
int col=mid%matrix[0].length;
if(matrix[rol][col]==target)
{
return true;
}
if(matrix[rol][col]>target)
{
end=mid-1;
}
else
{
start=mid+1;
}
}
return false;
}
}
矩阵从右上角到左下角遍历
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int d=0;
int a=matrix.length-1;
int b=matrix[0].length-1;
while(b>=0&&d<=a)
{
int c=matrix[d][b];
if(c==target)
{
return true;
}
if(c>target)
{
b--;
}
else
{
d++;
}
}
return false;
}
}