Share 3 python solutions, very sample and easy to understand


  • 0
    class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        #solutin 1:just to judge target whether exist
        if not matrix:return False
        row,cols=len(matrix),len(matrix[0])
        for i in xrange(row):
            #if target>=matrix[i][0] and target<=matrix[i][len(matrix[0])-1]:
            if target in matrix[i]:
                return True
        return False
        #solution 2:to find the location of target
        if not matrix:return False
        row,cols=len(matrix),len(matrix[0])
        for i in xrange(row):
            if target>=matrix[i][0] and target<=matrix[i][len(matrix[0])-1]:
                for j in xrange(cols):
                    if target== matrix[i][j]:
                        return True
        return False
        #solution 3:binary search
        if not matrix:return False
        row,cols=len(matrix),len(matrix[0])
        left,right=0,len(matrix[0])-1
        for i in xrange(row):
            if target>=matrix[i][0] and target<=matrix[i][len(matrix[0])-1]:
                while left<=right:
                    mid=(left+right)/2
                    if matrix[i][mid]==target:
                        return True
                    elif matrix[i][mid]>target:
                        right=mid-1
                    else:
                        left=mid+1
        return False

Log in to reply
 

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