【力扣100】74.搜索二维矩阵 || 列表推导式

添加链接描述

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        # 把距阵变成列表,然后二分查找
        nums=[]
        m=len(matrix)
        n=len(matrix[0])
        for i in range(m):
            for j in range(n):
                nums.append(matrix[i][j])
        left,right=0,len(nums)-1
        if target<nums[0] or target>nums[right]:
            return False
        while left<=right:
            mid=left+(right-left)//2
            if target==nums[mid]:
                return True
            elif target<nums[mid]:
                right=mid-1
            else:
                left=mid+1
        return False
        

思路:

  1. 暴力求解
  2. 把矩阵降维,然后使用二分搜索


列表推导式

将二维数组变为一维数组中,使用列表推导式,会更加简便

python 复制代码
# 二维矩阵
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# 将二维矩阵转换为一维列表
flat_list = [element for row in matrix for element in row]

print(flat_list)


解法二:

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m=len(matrix)
        n=len(matrix[0])
        i,j=0,m*n-1
        while i<=j:
            mid=i+(j-i)//2
            x=mid // n
            y=mid % n
            if target==matrix[x][y]:
                return True
            elif target<matrix[x][y]:
                j=mid-1
            else:
                i=mid+1
        return False

思路:

  1. 同样是二分查找,把mid对应的二维坐标找到就可以了
相关推荐
sali-tec2 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java2 小时前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20193 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_796826524 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme4 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5125 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8245 小时前
计数if|
算法
a伊雪6 小时前
c++ 引用参数
c++·算法
圣保罗的大教堂6 小时前
leetcode 3531. 统计被覆盖的建筑 中等
leetcode