The problem is to determine if a target integer exists within a given m * n
matrix. The matrix has two important
properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
These properties imply that the entire matrix can be treated as a single sorted list. Consequently, we can use binary
search to achieve the desired O(log(m * n))
time complexity.
The approach involves treating the 2D matrix as a 1D sorted array and applying binary search. Here are the detailed steps:
- Initialize pointers: Define two pointers:
leftIndex
starting at 0 andrightIndex
atm * n - 1
(the total number of elements minus one). - Binary Search:
- Compute the middle index of the current search range.
- Convert this 1D middle index back into 2D matrix coordinates to access the matrix element.
- Compare the matrix element at the middle coordinates with the target:
- If it matches the target, return
true
. - If the matrix element is less than the target, narrow the search to the right half by updating
leftIndex
. - If the matrix element is greater than the target, narrow the search to the left half by updating
rightIndex
.
- If it matches the target, return
- Termination: If the
leftIndex
exceeds therightIndex
, the target is not present in the matrix. Returnfalse
.
- Time Complexity:
O(log(m * n))
. The binary search divides the search space in half at each step, leading to a logarithmic time complexity. - Space Complexity:
O(1)
. The algorithm uses a constant amount of extra space for the pointers and the middle index calculation.