LeetCode face questions 04. Find two-dimensional array (Python)

Title
Here Insert Picture Description
Note: the same problem with the master 240 according to the present topic: https: //leetcode-cn.com/problems/search-a-2d-matrix-ii/
Source: stay button (LeetCode)
Link: https: // leetcode-cn. com / problems / er-wei- shu-zu-zhong-de-cha-zhao-lcof

Solution a: violence, traversing two-dimensional array, the time complexity of m * n

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: 
        if matrix==None or len(matrix)==0:
            return False
        rows = len(matrix)  # 矩阵行数
        columns = len(matrix[0])  # 矩阵列数
        for i in range(rows):
            for j in range(columns):
                if matrix[i][j]==target:
                    return True
        return False

Solution two: two-dimensional array because each row from left to right in order of ascending sort, each line traversing two-dimensional array, use a binary search to find methods for each row

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        if matrix==None or len(matrix)==0:
            return False
        rows = len(matrix)
        for i in range(rows):
            start = 0
            end = len(matrix[i])-1
            while start <= end:  #  对每一行用二查找方法查找
                mid = start+(end-start)//2
                if matrix[i][mid]>target:
                    end = mid-1
                elif matrix[i][mid]<target:
                    start = mid+1
                else:
                    return True
        return False

Solution three: start from the bottom left to determine, if the lower left corner of numbers larger than the target, delete the row; on the contrary, where the delete column, gradually approaching the upper right corner

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        if matrix==None and len(matrix)==0:
            return False
        rows = len(matrix)-1
        columns = 0
        while rows>=0 and columns<=len(matrix[0])-1:
            if matrix[rows][columns]>target:
                rows -= 1
            elif matrix[rows][columns]<target:
                columns += 1
            else:
                return True
        return False
Released eight original articles · won praise 0 · Views 110

Guess you like

Origin blog.csdn.net/weixin_43346653/article/details/104327242