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

1.题目描述

2.思路

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

方法2:学习Krahets佬的思路,从搜索矩阵的左下角开始遍历,matrixij > target时消去第i行,matrixij < 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 小时前
【无标题】
数据结构·算法
Kx_Triumphs3 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎3 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀4 小时前
约瑟夫环问题
算法
科技大视界6 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴6 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe6 小时前
算法滑动窗口
数据结构·算法
怪兽学LLM6 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
可编程芯片开发6 小时前
基于PI控制的三相整流器控制系统的simulink建模与仿真,包含超级电容充电和电机
算法