Search a Sorted Matrix
Medium matrix · binary-search
Description
Constraints
1 <= rows, cols <= 300
Examples
Input: matrix = [[1,4,7],[2,5,8],[3,6,9]], target = 5
Output: true
Hints (1)
- Start at the top-right corner and move left or down.
Solutions
Staircase from top-right. · Time O(rows+cols) · Space O(1)
func searchMatrix(matrix [][]int, target int) bool {
r, c := 0, len(matrix[0])-1
for r < len(matrix) && c >= 0 {
if matrix[r][c] == target {
return true
}
if matrix[r][c] > target {
c--
} else {
r++
}
}
return false
}
Staircase from top-right. · Time O(rows+cols) · Space O(1)
function searchMatrix(matrix, target) {
let r = 0, c = matrix[0].length - 1;
while (r < matrix.length && c >= 0) {
if (matrix[r][c] === target) return true;
if (matrix[r][c] > target) c--; else r++;
}
return false;
}
Staircase from top-right. · Time O(rows+cols) · Space O(1)
function searchMatrix($matrix, $target) {
$r = 0; $c = count($matrix[0]) - 1;
while ($r < count($matrix) && $c >= 0) {
if ($matrix[$r][$c] === $target) { return true; }
if ($matrix[$r][$c] > $target) { $c--; } else { $r++; }
}
return false;
}
Staircase from top-right. · Time O(rows+cols) · Space O(1)
def searchMatrix(matrix, target):
r, c = 0, len(matrix[0]) - 1
while r < len(matrix) and c >= 0:
if matrix[r][c] == target:
return True
if matrix[r][c] > target:
c -= 1
else:
r += 1
return False
Staircase from top-right. · Time O(rows+cols) · Space O(1)
function searchMatrix(matrix: number[][], target: number): boolean {
let r = 0, c = matrix[0].length - 1;
while (r < matrix.length && c >= 0) {
if (matrix[r][c] === target) return true;
if (matrix[r][c] > target) c--; else r++;
}
return false;
}
Create a free account to submit solutions, track progress and save problems.
Create account