Scribbling

LeetCode: 74. Search a 2D Matrix 본문

Computer Science/Coding Test

LeetCode: 74. Search a 2D Matrix

focalpoint 2021. 9. 28. 21:20
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if target < matrix[0][0] or target > matrix[-1][-1]:
            return False
        m, n = len(matrix), len(matrix[0])
        
        row = 0
        # row search
        l, r = 0, m - 1
        while l <= r:
            mid = (l + r) // 2
            if matrix[mid][0] > target:
                r = mid - 1
            else:
                row = max(row, mid)
                l = mid + 1
        
        # column search
        l, r = 0, n - 1
        while l <= r:
            mid = (l + r) // 2
            if matrix[row][mid] == target:
                return True
            if matrix[row][mid] < target:
                l = mid + 1
            else:
                r = mid - 1
        return False

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 77. Combinations  (0) 2021.09.28
LeetCode: 75. Sort Colors  (0) 2021.09.28
LeetCode: 73. Set Matrix Zeroes  (0) 2021.09.28
LeetCode: 72. Edit Distance  (0) 2021.09.26
LeetCode: 71. Simplify Path  (0) 2021.09.26