搜索二维矩阵中的target——二分查找或者二叉搜索树(python)

复制代码
#方法一
#利用有序的特点,使用二叉搜索树的思想
class Solution:
    def searchMatrix(self,matrix:List[List[int]],target:int)->bool:
        if not matrix or not matrix[0]:
            return False
        rows=len(matrix)  #行
        cols=len(matrix[0])  #列
        r,c=0,cols-1   #起点,右上角
        while 0<=r<rows and 0<=c<cols:
            if matrix[r][c]==target:
                return True
            elif matrix[r][c]<target:
                r+=1
            else:
                c-=1
        return False
        

#方法二
class Solution:
    def searchMatrix(self,matrix:List[List[int]],target:int)->bool:
        if not matrix or not matrix[0]:
            return False
        rows=len(matrix)
        cols=len(matrix[0])
        for i in range(rows):
            if target>matrix[i][cols-1]:   #如果不在这一行,就在下一行
                continue
            if target in matrix[i]:  #检查是否在该行
                return True
        return False

思路:

这个二维矩阵,从左到右有序,从上到下有序,所以需要利用这个特点:

方法一:利用二叉搜索树的思想,从右上角出发开始寻找target,要么往左走,要么往右走,走的过程中,需要判断是否越界。

方法二:利用二分查找的思想,先找出目标值在哪一行,定位到行之后,再从该行里面去找。

相关推荐
YJlio20 小时前
7.4.5 Windows 11 企业网络连接与网络重置实战:远程访问、本地策略与故障恢复
前端·chrome·windows·python·edge·机器人·django
深耕AI20 小时前
【VS Code避坑指南】点击Python图标提示“没有Python环境”,选择安装uv后这堆输出到底是什么意思?
开发语言·python·uv
第一程序员20 小时前
Rust生命周期管理实战指南:从困惑到掌握
python·github
程序员威哥20 小时前
实战!Python爬京东商品评论:从采集到情感分析+词云可视化,新手30分钟跑通
开发语言·爬虫·python·scrapy
风噪20 小时前
centos7 python3.13全套安装(可用于离线复制)
python
小陈的进阶之路21 小时前
Python系列课(5)——数据容器
windows·python
知识领航员21 小时前
2026年推荐6个AI音乐工具
java·人工智能·python·eclipse·django·php·pygame
PieroPc21 小时前
证件裁切拼版工具
python
2401_8330336221 小时前
golang如何实现MQTT主题通配符路由_golang MQTT主题通配符路由实现策略
jvm·数据库·python
AI精钢21 小时前
修复 AI Gateway 图片 MIME 类型错误:用魔数检测替代扩展名猜测
网络·人工智能·python·gateway·aigc