2022年2月25日
文章目录剑指Offer 04:二维数组中的查找一、问题描述二、问题分析三、解题代码总结
一、问题描述
在一个 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
二、问题分析问题的核心在于如何不用遍历来寻找给定数字。题目所给条件为有序数组,某数字右下方的数字都比它大,考虑从右上方开始向左下方搜索,当target比当前数字小的时候,将列数-1,当target比当前数字大的时候,将行数+1。代码的实现机理如下:(a)创建row指针和col指针,分别为0和列数-1;(b)当指针不越界时不断循环;(c)每次循环中,当target比当前数字小的时候,将列数-1,当target比当前数字大的时候,将行数+1,当target和当前数字相等的时候,返回True;(d)若直到指针越界都没找到,返回False。 三、解题代码
class Solution(object):
def findNumberIn2DArray(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
row = len(matrix)
try:
col = len(matrix[0])
except:
return False
col_ind = col - 1
row_ind = 0
while row_ind < row and col_ind >= 0:
if target < matrix[row_ind][col_ind]:
col_ind = col_ind - 1
elif target > matrix[row_ind][col_ind]:
row_ind = row_ind + 1
elif target == matrix[row_ind][col_ind]:
return True
return False
总结
从右上方向左下方搜索,时间复杂度为O(m+n)。



