Python OOP binary search


  • 0
    J
    from bisect import bisect
    
    
    class Matrix2List(object):
        def __init__(self, matrix):
            self.matrix = matrix
            self.col_len = len(matrix)
            self.row_len = len(matrix[0]) if self.col_len else 0
            self.len_ = self.col_len * self.row_len
    
        def __getitem__(self, idx):
            pos = idx + 1
            a, b = divmod(pos, self.row_len)
            if b == 0:
                return self.matrix[a - 1][-1]
            else:
                return self.matrix[a][b - 1]
    
        def __len__(self):
            return self.len_
    
    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            l = Matrix2List(matrix)
            if len(l) == 0:
                return False
    
            idx = bisect(l, target) - 1
            if 0 <= idx < len(l) and l[idx] == target:
                return True
            return False
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.