lc 搜索二维矩阵 II

链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

代码:

class Solution(object):
    def searchMatrix(self, matrix, target):
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return False
        
        m = len(matrix)
        n = len(matrix[0])

        row = m-1
        col = 0

        while col < n and row >= 0:
            if matrix[row][col] > target:
                row -= 1
            elif matrix[row][col] < target:
                col += 1
            else:
                return True
        
        return False
View Code

思路:递归,每次用 lower_bound 舍弃至多一半矩阵,代码很麻烦,还剩三个样例的时候 TLE 了,最差情况是 O(m*n)。正是因为 lowerbound 啊..

若从矩阵的左下角开始,效果是一样的,发现总可以舍弃左上或者右下一整个数组,复杂度 O(m+n)。

posted on 2020-05-23 00:25  FriskyPuppy  阅读(142)  评论(0编辑  收藏  举报

导航