Monday, September 8, 2014

Leetcode: Search a 2D Matrix @Python

class Solution:
    # @param matrix, a list of lists of integers
    # @param target, an integer
    # @return a boolean
    def searchMatrix(self, matrix, target):
        rlen=len(matrix)
        clen=len(matrix[0])
        if rlen*clen==0:
            return False
        l_idx=0
        r_idx=rlen*clen-1
        if target<matrix[0][0] or target >matrix[rlen-1][clen-1]:
            return False
        while l_idx<=r_idx:
            mid=(l_idx+r_idx)//2
            if target>matrix[mid//clen][mid%clen]:
                l_idx=mid if l_idx<mid else l_idx+1
            elif target==matrix[mid//clen][mid%clen]:
                return True
            else:
                r_idx=mid if r_idx>mid else r_idx-1
        return False      

No comments :

Post a Comment