2.二维数组中的查找

128 阅读1分钟

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例:

现有矩阵 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false

限制:

0 <= n <= 1000
0 <= m <= 1000

答案1:

暴力解法

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        for l in matrix:
            if target in l:
                return True
        return False

时间复杂度O(m*n) 如果在面试中你采用这种方式解答、估计面试官直接说 “今天的面试就到这里吧”

答案二:

在一个有序的二维数组中进行从右上角至左下角(或者左下角到右上角)的index数字判断、如果该index大于target 则列减1 如果小于则行减一的类似于二叉树搜索算法。

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return False
        m = len(matrix)
        n = len(matrix[0])
        row = 0
        col = n - 1
        while row <= m-1 and col >=0:
            if matrix[row][col] == target:
                return True
            elif matrix[row][col] > target:
                col -= 1
            else:
                row += 1
        return False