Leetcode 240. Search a 2D Matrix II
Write an efficient algorithm to search for a value in an m x n
matrix. This matrix has the following properties:
Given the matrix and a target value, return true
if the target is found in the matrix, and false
otherwise.
Example 1:
Input: 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 = 5
Output: true
Example 2:
Input: 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 = 20
Output: false
false
.To efficiently search the matrix, leverage its sorted properties:
true
.public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int row = 0;
int col = cols - 1; // start from the top-right corner
while (row < rows && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--; // move left
} else {
row++; // move down
}
}
return false;
}
}
m
is the number of rows and n
is the number of columns.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?