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
The simplest way to search for a target in a 2D matrix is to iterate through each element until we find the target or exhaust all possibilities. This approach mimics a direct linear search, which is straightforward but inefficient for large matrices.
Given that the rows of the matrix are sorted in non-decreasing order and each first integer of a row is greater than the last integer of the previous row, each row can independently be subjected to a binary search to determine if the target exists therein. This approach capitalizes on this sorted property, reducing the search space more efficiently than a linear scan.
By treating the 2D matrix as a sorted 1D array, we can perform a single binary search to find the target. The index conversion between the 1D and 2D matrix can be done using simple row and column calculations. This method fully utilizes the sorted property of the entire matrix, leading to an extremely efficient solution.