You are given an m x n integer matrix matrix with the following two properties:
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
From: LeetCode
Link: 74. Search a 2D Matrix
1. Mapping 2D to 1D: Even though the matrix is 2-dimensional, we can view it as a 1-dimensional array (by stacking rows one after the other). For instance, in a matrix with n columns, the element in the 2nd row and 1st column can be accessed by the index n of our “flattened” array.
2. Binary Search: We define two pointers, left and right, to represent the start and end of our current search space. Initially, left is at the beginning and right is at the end of our “flattened” matrix.
3. Midpoint Calculation: For each iteration, we find the midpoint of our current search space. We then convert this midpoint index into its corresponding 2D matrix coordinates using the formulas:
4. Comparison: Once we have the 2D coordinates for our midpoint, we can retrieve the value from the matrix and compare it to our target:
5. Convergence: We continue the binary search process, narrowing down our search space, until our left pointer exceeds the right pointer or we find the target.
6. Result: If we’ve gone through the entire search space without finding the target, we return false. Otherwise, we return true when we find the target.
bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target) {
int m = matrixSize;
int n = *matrixColSize;
int left = 0, right = m * n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int mid_value = matrix[mid / n][mid % n];
if (mid_value == target) {
return true;
} else if (mid_value < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}