LeetCode Python - 74. 搜索二维矩阵

目录


题目描述

给你一个满足下述两条属性的 m x n 整数矩阵:

  • 每行中的整数从左到右按非严格递增顺序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。

示例 1:

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3

输出:true

示例 2:

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13

输出:false

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

解法

方法一:二分查找

我们将二维矩阵逻辑展开,然后二分查找即可。

时间复杂度 O(log(m×n))。其中 m 和 n 分别是矩阵的行数和列数。空间复杂度 O(1)。

python 复制代码
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        m, n = len(matrix), len(matrix[0])
        left, right = 0, m * n - 1
        while left < right:
            mid = (left + right) >> 1
            x, y = divmod(mid, n)
            if matrix[x][y] >= target:
                right = mid
            else:
                left = mid + 1
        return matrix[left // n][left % n] == target

方法二:从左下角或右上角搜索

这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 matrix[i][j] 与 target 的大小关系:

  • 若 matrix[i][j]=target,说明找到了目标值,直接返回 true。
  • 若 matrix[i][j]>target,说明这一行从当前位置开始往右的所有元素均大于 target,应该让 i 指针往上移动,即
    i=i−1。
  • 若 matrix[i][j]<target,说明这一列从当前位置开始往上的所有元素均小于 target,应该让 j 指针往右移动,即
    j=j+1。

若搜索结束依然找不到 target,返回 false。

时间复杂度 O(m+n)。其中 m 和 n 分别是矩阵的行数和列数。空间复杂度 O(1)。

python 复制代码
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        m, n = len(matrix), len(matrix[0])
        i, j = m - 1, 0
        while i >= 0 and j < n:
            if matrix[i][j] == target:
                return True
            if matrix[i][j] > target:
                i -= 1
            else:
                j += 1
        return False

运行结果

方法一

方法二

相关推荐
船长@Quant5 分钟前
数学视频动画引擎Python库 -- Manim Voiceover 语音服务 Speech Services
python·数学·manim·动画引擎·语音旁白
张晓~183399481211 小时前
数字人分身+矩阵系统聚合+碰一碰发视频: 源码搭建-支持OEM
线性代数·矩阵·音视频
好开心啊没烦恼1 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20202 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
空中湖2 小时前
tensorflow武林志第二卷第九章:玄功九转
人工智能·python·tensorflow
CodeCraft Studio3 小时前
CAD文件处理控件Aspose.CAD教程:使用 Python 将绘图转换为 Photoshop
python·photoshop·cad·aspose·aspose.cad
Two_brushes.4 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
Python×CATIA工业智造5 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco6 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
狐凄6 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python