力扣刷题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应该还可以优化的但实在没精力了。

相关推荐
踩坑记录1 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
Z1Jxxx1 小时前
01序列01序列
开发语言·c++·算法
汽车仪器仪表相关领域3 小时前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试
Doro再努力3 小时前
【数据结构08】队列实现及练习
数据结构·算法
清铎4 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
linweidong5 小时前
嵌入式电机:如何在低速和高负载状态下保持FOC(Field-Oriented Control)算法的电流控制稳定?
stm32·单片机·算法
踩坑记录5 小时前
leetcode hot100 42 接雨水 hard 双指针
leetcode
net3m335 小时前
单片机屏幕多级菜单系统之当前屏幕号+屏幕菜单当前深度 机制
c语言·c++·算法
mmz12075 小时前
二分查找(c++)
开发语言·c++·算法
Insight5 小时前
拒绝手动 Copy!一文吃透 PyTorch/NumPy 中的广播机制 (Broadcasting)
算法