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.
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]
]
给出二维矩阵,矩阵的特点是每行排序,每列排序,与之前不同的是上一行的最后一个元素并不小于下一行的第一个元素。所以不能按binary search以行为单位查找范围。
思路:
以右上角元素为起点,如果target<右上角元素,那么就可以排除最右边一列,因为列是按升序排列的,col–
如果target>右上角元素,那么row++,即从下一行开始找
直到最后一行,第一列
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = 0;
int col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (target == matrix[row][col]) {
return true;
} else if (target < matrix[row][col]) {
col --;
} else {
row ++;
}
}
return false;
}