|
| 1 | +""" |
| 2 | + Write an efficient algorithm that searches for a value in an m x n matrix. |
| 3 | + This matrix has the following properties: |
| 4 | + - Integers in each row are sorted from left to right. |
| 5 | + - The first integer of each row is greater than the last integer of the |
| 6 | + previous row. |
| 7 | + |
| 8 | + Example: |
| 9 | + Input: |
| 10 | + matrix = [ |
| 11 | + [1, 3, 5, 7], |
| 12 | + [10, 11, 16, 20], |
| 13 | + [23, 30, 34, 50] |
| 14 | + ] |
| 15 | + target = 3 |
| 16 | + Output: true |
| 17 | +""" |
| 18 | +#Difficulty: Medium |
| 19 | +#136 / 136 test cases passed. |
| 20 | +#Runtime: 64 ms |
| 21 | +#Memory Usage: 15.9 MB |
| 22 | + |
| 23 | +#Runtime: 64 ms, faster than 84.49% of Python3 online submissions for Search a 2D Matrix. |
| 24 | +#Memory Usage: 15.9 MB, less than 5.88% of Python3 online submissions for Search a 2D Matrix |
| 25 | + |
| 26 | +class Solution: |
| 27 | + |
| 28 | + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: |
| 29 | + if not matrix or not matrix[0]: return |
| 30 | + self.rows = len(matrix) - 1 |
| 31 | + self.cols = len(matrix[0]) - 1 |
| 32 | + return self.binarySearchRow(0, self.rows, matrix, target) |
| 33 | + |
| 34 | + def binarySearchRow(self, left, right, matrix, target): |
| 35 | + while left <= right: |
| 36 | + mid = (left + right) // 2 |
| 37 | + if matrix[mid][0] <= target <= matrix[mid][-1]: |
| 38 | + return self.binarySearchTarget(0, self.cols, matrix[mid], target) |
| 39 | + if matrix[mid][0] < target: |
| 40 | + left = mid + 1 |
| 41 | + else: |
| 42 | + right = mid - 1 |
| 43 | + |
| 44 | + def binarySearchTarget(self, left, right, matrix, target): |
| 45 | + while left <= right: |
| 46 | + mid = (left + right) // 2 |
| 47 | + if matrix[mid] == target: |
| 48 | + return True |
| 49 | + if matrix[mid] < target: |
| 50 | + left = mid + 1 |
| 51 | + else: |
| 52 | + right = mid - 1 |
| 53 | + return False |
0 commit comments