1. 程式人生 > 實用技巧 >LeetCode #74 Search a 2D Matrix

LeetCode #74 Search a 2D Matrix

題目

Search a 2D Matrix


解題方法

實質上就是先對第一列進行二分查詢,再對比較小的那個行做行內二分查詢。注意二分查詢選擇結束值的時候,這裡要選below,即right值,因為是要在小的那一行找,如果選了above就是在大的那一行找了,就錯了。


程式碼

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix or not matrix[0]:
            return False
        
        m = len(matrix)
        n = len(matrix[0])
        row = 0
        
        above = 0
        below = m - 1
        while above <= below:
            mid = (above + below) // 2
            if matrix[mid][0] == target:
                return True
            elif matrix[mid][0] > target:
                below = mid - 1
            else:
                above = mid + 1
        row = below
        
        left = 0
        right = n - 1
        while left <= right:
            mid = (left + right) // 2
            if matrix[row][mid] == target:
                return True
            elif matrix[row][mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        return False