当前位置: 首页 > 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

http://www.xdnf.cn/news/1015219.html

相关文章:

  • 贫血模型与充血模型
  • 从0到1:Dify AI智能体部署与使用全攻略
  • 如何存储和和使用比特币---第1关:比特币的存储
  • 机器学习--分类
  • Kafka入门4.0.0版本(基于Java、SpringBoot操作)
  • [Godot] C#读取CSV表格创建双层字典实现本地化
  • Yarn与NPM缓存存储目录迁移
  • c++ std::function
  • MySQL查询缓存深度剖析
  • 多环境开发配置,Spring boot
  • RK3576 Android14 DMIC调制
  • 前端构建工具Webapck、Vite——>前沿字节开源Rspack详解——2023D2大会
  • 打卡第44天:无人机数据集分类
  • android过渡动画
  • 【Pytorch】(1)Pytorch环境安装-①创建虚拟环境
  • NB-IoT-下行同步、广播信道和信号
  • Volta 管理 Node 版本最佳实践教程
  • 【CATIA的二次开发28】抽象对象Document涉及应用程序连接的属性
  • python中的面向对象:继承、封装、多态
  • 中小企业数字化转型:如何选择靠谱的软件开发服务商?
  • 【知识图谱构建系列2】LLM4KGC项目安装运行
  • Profinet转Modbus网关:破解热处理炉协议壁垒的温控通讯密码
  • Python图片格式转换工具深度解析[附源码】
  • Blender 4.4.3三维动画建模和渲染软件Win/Mac双端资源下载
  • RDMA简介7之RoCE v2可靠传输
  • 包含11个整套APP移动端UI的psd适用于旅行聊天交友相关的社交应用程序
  • 机器学习中的数据准备关键技术
  • iOS性能调试完整流程实录:工具组合下的问题定位与修复实践(含keymob)
  • 云端求解热方程:源于傅里叶的洞察-AI云计算数值分析和代码验证
  • 前端处理后端对象类型时间格式通用方法封装,前端JS处理JSON 序列化后的格式 java.time 包中的日期时间类