Leetcode 74. Search a 2D Matrix
You are given a matrix matrix
with m
rows and n
columns, and an integer target
. The matrix has the following properties:
Write an efficient algorithm that searches for a value in the matrix. Return true
if the value is found, and false
otherwise.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
false
.Given that the matrix is sorted in a specific way, each row starts with a number larger than the last number of the previous row and within each row, the numbers are sorted. This makes it similar to a 1D sorted array and suggests that we can use a binary search algorithm:
totalElements = m * n
.left
at 0 and right
at totalElements - 1
) for the binary search.middle / n
(integer division)middle % n
(remainder)target
, return true
.target
, move left
to middle + 1
.target
, move right
to middle - 1
.left
exceeds right
.false
.#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 left = 0;
int right = m * n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int midValue = matrix[mid / n][mid % n];
if (midValue == target) {
return true;
} else if (midValue < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
};
The time complexity of this approach is O(log(m * n))
, since we are using binary search on a range that contains m * n
elements.
The space complexity is O(1)
because we are only using a few additional variables that do not scale with input size.
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?