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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
根据题目给定数组的性质:如果从这个二维数组的最右上角元素开始判断,当target<该元素时,可以排除它所在的一列,当target>该元素时,则可以排除其所在的一行。AC码如下:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0||matrix[0].length==0||matrix==null)return false;
int row = matrix.length-1;
int indexcolumn = matrix[0].length-1;
int indexrow = 0;
while(indexrow<=row && indexcolumn>=0){
if(matrix[indexrow][indexcolumn]==target){
return true;
}else if(matrix[indexrow][indexcolumn]>target){
indexcolumn--;
}else if(matrix[indexrow][indexcolumn]<target){
indexrow++;
}
}
return false;
}
}