题目
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.
我的想法
从左下角开始找,如果target < cur则往上移一行,如果target > cur则往右移一列
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) {
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int row = rows - 1;
int col = 0;
while(row >= 0 && col < cols) {
if(matrix[row][col] == target) {
return true;
}
if(matrix[row][col] > target) {
row--;
} else if(matrix[row][col] < target) {
col++;
}
}
return false;
}
}