
Sponsored
Sponsored
This approach begins searching from the top-right corner of the matrix. If the current element is equal to the target, return true. If the current element is greater than the target, move left. If the current element is less than the target, move down. This method effectively narrows down the search space, taking advantage of the sorted property of the matrix.
Time Complexity: O(m + n), where m is the number of rows and n is the number of columns.
Space Complexity: O(1), as no extra space is used.
1def searchMatrix(matrix, target):
2 row, col = 0, len(matrix[0]) - 1
3 while row < len(matrix) and col >= 0:
4 if matrix[row][col] == target:
5 return True
6 elif matrix[row][col] > target:
7 col -= 1
8 else:
9 row += 1
10 return FalseThe Python implementation makes use of similar logic as other language solutions, taking advantage of Python's simplicity and dynamic typing to efficiently track indices and compare values.
This approach uses binary search on each row of the matrix. Since each row is sorted, binary search can efficiently determine if the target exists within the row. If found in any row, the function returns true.
Time Complexity: O(m * log(n)), where m is the number of rows and n is the number of columns.
Space Complexity: O(1).
1def
The Python function defines an internal helper `binary_search` which operates on each row. It iteratively applies binary search to rows, leveraging the sorted property to quickly declutter impossible sections.