当前位置: 首页 > news >正文

HOT 100 | 73.矩阵置零、54.螺旋矩阵、48.旋转图像

一、73. 矩阵置零

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

 1. 解题思路

1. 使用两个数组分别标记每行每列是否有0,初始化全为False,遇到0就变成True。

2. 遍历矩阵,遇到0就将False改成True。

3. 再次遍历矩阵,更新原数组,将0的行列置为0。

2. 代码实现

class Solution:def setZeroes(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""m, n = len(matrix), len(matrix[0])row, col = [False]*m, [False]*nfor i in range(m):for j in range(n):if matrix[i][j] == 0:row[i] = col[j] = Truefor i in range(m):for j in range(n):if row[i] or col[j]:matrix[i][j] = 0

二、54.螺旋矩阵

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

1. 解题思路

(1)判断传入的矩阵是否具备合法性,不合法就直接返回空数组。

(2)定义res空数组,用于存储最终的结果。

(3)定义四个变量,分别是矩阵的四个边界。

        

2. 代码实现

class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:if not matrix or not matrix[0]:return []res = []left,right = 0, len(matrix[0])-1top, bottom = 0, len(matrix)-1while left <= right and top <= bottom:for i in range(left, right+1):res.append(matrix[top][i])for i in range(top+1, bottom+1):res.append(matrix[i][right])if left < right and top < bottom:for i in range(right-1, left, -1):res.append(matrix[bottom][i])for i in range(bottom, top, -1):res.append(matrix[i][left])left += 1right -= 1top += 1bottom -= 1return res

三、48.旋转图像

1. 解题思路

(1)使用逐层旋转的方法,由于是n*n的矩阵,所以只需要定义left和right的初始值即可: left, right = 0, len(matrix)。left和right初始值分别直接赋值给top和bottom即可。

(2)定义一个单独的变量topleft,用于存储左上角的数值,方便后面进行交换。

(3)逐层进行旋转,也就是先逐次旋转四个顶点,也就是进行值的交换,然后旋转偏移量为i的元素。

2. 代码实现

class Solution:def rotate(self, matrix: List[List[int]]) -> None:left, right = 0, len(matrix)-1while left < right:for i in range(right-left):top, bottom = left, righttopleft = 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] = topleftleft+=1right-=1

相关文章:

  • 浪潮下的机器人竞技与创新突破 ——QOGRISYS O9201 系列模组赋能智能未来
  • 优傲机器人推出全新关节扭矩直接控制技术,助力科研与AI应用创新
  • 【Docker】docker 常用命令
  • 【MySQL基础】表的约束的类型与使用指南
  • 自主 Shell 命令行解释器
  • Spring Boot排查与解决JSON解析错误(400 Bad Request)的详细指南
  • 打卡第44天:无人机数据集分类
  • LeetCode 704.二分查找
  • 【Qt】信号与槽
  • 深度解析Linux用户生态:账户架构设计与系统运维实战技巧》
  • 轻量级密码算法PRESENT的C语言实现(无第三方库)
  • Vue3 + TypeScript 操作第三方库(Element Plus 的 ElTable)的内部属性
  • 性能优化相关
  • 将 App 安装到 iPhone 真机上测试
  • 安装 Ubuntu Desktop 2504
  • FastChat 架构拆解:打造类 ChatGPT 私有化部署解决方案的基石
  • 深度学习——基于PyTorch的MNIST手写数字识别详解
  • java_oss_微信小程序_通过临时签名url访问oss中存储的图像
  • SpringCloud2020-alibaba
  • 第32节 Node.js 全局对象
  • 益阳注册公司/免费网站分析seo报告是坑吗
  • 桐乡市住房建设局网站公示/零基础学seo要多久
  • 做外贸怎么打开国外网站/武汉网站seo公司
  • 网络网站排名优化/百度域名
  • 买卖域名的网站好/企业如何进行网络营销
  • 黄石网站建设教程/做个小程序需要花多少钱