240. Search a 2D Matrix II




the idea is to start from the right top corner (biggest in this row), so we can conclude:
current value == target, return true
current value > target, should do col--, or
should row++, find next row
time: O(m+n)
space: O(1)
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int row = 0;
int col = n - 1;
while (col >= 0 && row < m) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}
}
Last updated
Was this helpful?