Staircase from the top-right
Time O(m + n) Space O(1)If the value is larger than target, discard the column (move left); if smaller, discard the row (move down).
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]], target = 5Step 1/5Start at the top-right: 15. It is bigger than 5, so the whole last column (15 and below) is too big. Step left.
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int r = 0, c = matrix[0].length - 1;
while (r < matrix.length && c >= 0) {
int v = matrix[r][c];
if (v == target) return true;
if (v > target) c--; else r++;
}
return false;
}
}Verdict: Simpler and faster than recursive quadrant splitting.