hot100-矩阵

73. 矩阵置0

73. 矩阵置零 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        # 简单的做法,使用一个标记矩阵,但是这样过于繁琐
        # 我们可以仅仅使用一个行向量数组和列向量数组进行标记
        m,n = len(matrix),len(matrix[0])
        row = [0] * m
        col = [0] * n
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    row[i] = col[j] = 1
        for i in range(m):
            for j in range(n):
                if row[i] or col[j]:
                    matrix[i][j] = 0
        return matrix

时间复杂度:O(mn)

空间复杂度:O(m+n)

54. 螺旋矩阵

54. 螺旋矩阵 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        # 一圈一圈转即可,有点儿递归的思想
        left = 0
        right = len(matrix[0])
        top = 0
        bottom = len(matrix)
        res = []
        # 当矩阵只有一行时,我们遍历了上,右会跳过,但是下还会遍历一遍,就会重复
        # 当矩阵只有一列时,我们遍历了上和右,但是左还会遍历,也会重复
        # 所以上和右是一定要遍历的,左和下要判断
        while top<bottom and left<right:
            for i in range(left,right):
                res.append(matrix[top][i])
            top += 1
            for j in range(top,bottom):
                res.append(matrix[j][right-1])
            right -= 1
            if top< bottom:
                for i in reversed(range(left,right)):
                    res.append(matrix[bottom-1][i])
                bottom -= 1
            if left< right:
                for j in reversed(range(top,bottom)):
                    res.append(matrix[j][left])
                left +=1
        return res

时间复杂度:O(mn)

空间复杂度:O(1)

48. 旋转图像

48. 旋转图像 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        # 数学上可证明,顺时针旋转90就等价于先水平翻转,然后转置
        n = len(matrix)
        if n<2:
            return
        for i in range(n//2):
            matrix[i],matrix[n-i-1] = matrix[n-i-1],matrix[i]
        for i in range(n):
            for j in range(i+1,n):
                matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]
        return
python 复制代码
class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        # 思路清奇但是好理解的方法:
        # 上下左右各取4个点,旋转90,然后位置++ 直到外层结束
        n = len(matrix)
        left = top = 0
        right = bottom = n-1
        for e in range(n//2):
            for i in range(n-2*e-1):
                # 一次性交换有问题,注意交换顺序
                # 先保存上
                tmp = matrix[top][left+i]
                # 左到上
                matrix[top][left+i] = matrix[bottom-i][left]
                # 下到左
                matrix[bottom-i][left] = matrix[bottom][right-i] 
                # 右到下
                matrix[bottom][right-i] = matrix[top+i][right]
                # 上到右
                matrix[top+i][right] = tmp
            left +=1
            top +=1
            bottom -=1
            right -=1

时间复杂度:O(nn)

空间复杂度:O(1)

240. 搜索二维矩阵 II

240. 搜索二维矩阵 II - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def binary_search(self, nums, target):
        left = 0
        right = len(nums)-1
        while left <= right:
            mid = (left+right) // 2
            if target == nums[mid]:
                return True
            elif target > nums[mid]:
                left = mid+1
            else:
                right = mid-1
        return False

    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # 每一行用二分查找
        for nums in matrix:
            if self.binary_search(nums,target):
                return True
        return False

时间复杂度:O(mlogn)

空间复杂度:O(1)

但是以上的做法没有用到列的单调信息。

python 复制代码
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # 从左往右递增,从上往下递增
        # 我们应该先尽快锁定要查找的列或者行
        # 而且我们希望仅仅通过一个元素的比较,就可以较快的舍弃
        # 右上角的元素a
        # 如果a大于target,那么这一列都会大于a,这一列舍弃
        # 如果a小于target,那么这一行都会小于a,这一行舍弃
        m = len(matrix)
        n = len(matrix[0])
        i = 0
        j = n -1
        while i<m and j >=0:
            if matrix[i][j] == target:
                return True
            if matrix[i][j] > target:
                j -=1
            if matrix[i][j] < target:
                i +=1
        return False

时间复杂度:O(m+n)

空间复杂度:O(1)

相关推荐
倒头就睡的小比特2 天前
算法竞赛C++常用的STL
c++·算法
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼2 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
m0_547486662 天前
《数据结构教程》全套 PPT课件2026
数据结构