Search a 2D Matrix
You are given an m x n integer matrix matrix and an integer target. Return true if target exists in matrix, or false otherwise.
The matrix has the following properties:
- Integers in each row are sorted in non-decreasing order from left to right.
- The first integer of each row is strictly greater than the last integer of the previous row.
Equivalently, concatenating the rows in order (row-major order) produces a single sorted array of m * n integers, so an efficient solution can treat the matrix as one virtual sorted 1D array.
Examples
Input: [[[1,3,5,7],[10,11,16,20],[23,30,34,60]],3]
Output: true
Input: [[[1,3,5,7],[10,11,16,20],[23,30,34,60]],13]
Output: false
Hints
Consider the matrix as a flattened 1D array where each row is concatenated sequentially. The total number of elements is `rows * cols`.
Perform a binary search on the virtual 1D array by calculating the middle index, then converting it to 2D coordinates (row, col) using integer division and modulus operations.
Optimize the search by leveraging the sorted property of the matrix: discard half of the search space in each iteration by comparing the target with the middle element and adjusting the search range accordingly.
Search a 2D Matrix
You are given an `m x n` integer matrix `matrix` and an integer `target`. Return `true` if `target` exists in `matrix`, or `false` otherwise.