搜索二维矩阵 II【矩阵】【二分】

本文详细介绍了四种在二维矩阵中搜索目标值的算法:暴力搜索、二分查找、使用bisect模块的二分法以及Z算法。分析了它们的时间复杂度和空间复杂度。
摘要由CSDN通过智能技术生成

Problem: 240. 搜索二维矩阵 II

思路 & 解题方法

暴力、二分、Z

复杂度

时间复杂度:

暴力: O ( m n ) O(mn) O(mn)
二分: O ( m l o g n ) O(mlogn) O(mlogn)
Z: O ( m + n ) O(m + n) O(m+n)

空间复杂度:

添加空间复杂度, 示例: O ( n ) O(n) O(n)

暴力

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for x in matrix:
            for num in x:
                if num == target:
                    return True
        return False

二分

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for x in matrix:
            left, right = 0, len(matrix[0]) - 1
            while left <= right:
                mid = (left + right) // 2
                if x[mid] > target:
                    right = mid - 1
                elif x[mid] < target:
                    left = mid + 1
                else:
                    return True
        return False

bisect

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for x in matrix:
            idx = bisect.bisect_left(x, target)
            if idx < len(x) and x[idx] == target:
                return True
        return False

Z

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        x, y = 0, n - 1
        while x < m and y >= 0:
            if matrix[x][y] == target:
                return True
            if matrix[x][y] > target:
                y -= 1
            elif matrix[x][y] < target:
                x += 1
        return False
  • 15
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alan_Lowe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值