【算法训练】剑指offer#04 二维数组中的查找

一、描述

剑指 Offer 04. 二维数组中的查找

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

示例 1:

[
  [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

二、思路

  • 还是暴力做吧..就将target与每行的行首和行尾进行比较,在范围内的再对改行进行检索
class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        n = len(matrix)
        m = len(matrix[0])
        print(n,m)
        for i in range(n):
            if matrix[i][0] == target or matrix[i][m-1] == target:
                return True
            if matrix[i][0] < target and matrix[i][m-1] > target:
                for j in matrix[i]:
                    print(j)
                    if j == target:
                        return True
                return False

理解错了,以为下一行的数一定比上一行的数大

  • 顺序遍历,该行出现比target大的数就下一行,改行没有比target小的数就false

三、解题

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        have_small = False
        for i in matrix:
            for j in i:
                if j < target:
                    have_small = True
                if j > target:
                    break
                if j == target:
                    return True
            if not have_small:
                return False
        else:
            return False
posted @ 2022-01-18 17:48  小拳头呀  阅读(0)  评论(0编辑  收藏  举报