Leetcode 240. Search a 2D Matrix II
LeetCode Problem 240: Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:
Example:
Consider the following 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]
]
Given target = 5
, return true
.
Given target = 20
, return false
.
true
.false
.To efficiently search the matrix given the sorted properties, we can use the following strategy:
matrix[0][n-1]
).true
.This strategy ensures that each step either moves down or left, and each element is visited at most once, resulting in a time complexity of O(m + n), where m
is the number of rows and n
is the number of columns.
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty()) return false;
int m = matrix.size();
int n = matrix[0].size();
int row = 0;
int col = n - 1;
while (row < m && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--; // move left
} else {
row++; // move down
}
}
return false; // target not found
}
};
This approach provides an efficient search mechanism for the given problem constraints.
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?