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

相关推荐
偷吃的耗子4 分钟前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn
dazzle1 小时前
机器学习算法原理与实践-入门(三):使用数学方法实现KNN
人工智能·算法·机器学习
那个村的李富贵1 小时前
智能炼金术:CANN加速的新材料AI设计系统
人工智能·算法·aigc·cann
张张努力变强1 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发1 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
张登杰踩1 小时前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao2 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0072 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
风暴之零2 小时前
变点检测算法PELT
算法
深鱼~2 小时前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann