题目:在一个二维数组上,每一行从左到右递增,每一列从上到下递增,高效的查找二维数组中是否有所要查找的数字target。
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =3, return true.
方法:从右上角查起;
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null)
return false;
int rows =matrix.length;
int cols =matrix[0].length;
if(rows ==0||cols == 0)
return false;
int row=0;
int col=cols-1;
while(row<rows&&col>=0)
{
if(matrix[row][col] == target)
{
return true;
}
else if(matrix[row][col]<target)
{
row++;
}
else
{
col--;
}
}
return false;
}