Given a m x n matrix, find a target number. Each row is sorted in ascending order from left to right. Each column is also sorted in ascending order from top to bottom.
This is different from each row is sorted and the start of next row is bigger than the end of the current row. We can't prune half of the matrix in this case. A O(logn) solution doesn't exist for this question.
Approach
So what we can do instead is pruning on a row or a column base on the information we have. Start from the lower left corner (or upper right).
x is col, y is row
start from matrix[m][0]
while x < matrix[0].length and y >= 0
if target > matrix[y][x]
x++
elif target < matrix[y][x]
y--;
else
return true
end while
Code
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int x = 0, y = matrix.length - 1;
while (x < matrix[0].length && y >= 0) {
if (target > matrix[y][x]) {
x++;
} else if (target < matrix[y][x]) {
y--;
} else {
return true;
}
}
return false;
}