力扣刷题Day 46:搜索二维矩阵 II(240)

1.题目描述

2.思路

方法1:分别找到搜索矩阵的右、下边界,然后从[0][0]位置开始遍历这部分矩阵搜索目标值。

方法2:学习Krahets佬的思路,从搜索矩阵的左下角开始遍历,matrix[i][j] > target时消去第i行,matrix[i][j] < target时消去第j列。

3.代码(Python3)

方法1:

复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if matrix[0][0] > target:
            return False
        m, n = len(matrix), len(matrix[0])
        bottom, right = m, n
        for k in range(m):
            if matrix[k][0] > target:
                bottom = k
                break
        for k in range(n):
            if matrix[0][k] > target:
                right = k
                break
        for i in range(bottom):
            for j in range(right):
                if matrix[i][j] == target:
                    return True
        return False

方法2:

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

4.执行情况

方法1:

方法2:

5.感想

今天好困,脑子不清醒,感觉我的方法1应该还可以优化的但实在没精力了。

相关推荐
超级码力6665 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
穿条秋裤到处跑5 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
Merlos_wind5 小时前
HashMap详解
算法·哈希算法·散列表
汉克老师6 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Yzzz-F8 小时前
Problem - 2205D - Codeforces
算法
智者知已应修善业9 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
Halo_tjn9 小时前
Java Set集合相关知识点
java·开发语言·算法
生成论实验室10 小时前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
AI科技星10 小时前
全域数学·72分册:场计算机卷【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算
科研前沿11 小时前
镜像孪生VS视频孪生核心技术产品核心优势
大数据·人工智能·算法·重构·空间计算