当前位置:网站首页>螺旋矩阵_数组 | leecode刷题笔记
螺旋矩阵_数组 | leecode刷题笔记
2022-08-04 01:00:00 【Begonia_cat】
59. 中等
螺旋矩阵II
题目:给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
.
示例:输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
思路:坚持循环不变量原则,自始至终坚持左闭右开区间可以用range()来实现,range是前开后闭的
,进行循环。【图片来自carl哥的代码随想录】
注意:含有n²
个元素的方形二维数组,其长宽均为n
!这个要搞清楚。
代码的第一步是:初始化一个n行n列的二维数组
,初始化为全零数组。
当n = 4时:
当n = 5时:
四个方向每步各次n-1
步,当n为奇数时,二维矩阵有中心点。∵
数组的下标是从0开始的,所以:
当n=3
时,中心点的索引为[1,1]
;
当n=5
时,中心点的索引为[2,2]
;∴
n为奇数时,索引坐标为[n//2, n//2]
从左至右,从上至下,从右至左,总下至上
为一次循环,n=3
时,循环1次
+1个中心点
n=4
时,循环2次
n=5
时,循环2次
+1个中心点
n=6
时,循环3次
循环次数=n//2
+1个中心点(n为奇数时)
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums = [[0] * n for _ in range(n)] # 初始化为n行n列的二维数组
startx, starty = 0, 0 #起始点为0行0列处
loop, mid = n//2, n//2 # 迭代次数、n为奇数时,矩阵的中心点
count = 1 # 计数
for offset in range(1, loop + 1):
for i in range(starty, n-offset): # 从左往右, startx保持不变, starty递增
nums[startx][i] = count
count += 1
for i in range(startx, n-offset): # 从上至下, starty保持不变,startx递增
nums[i][n-offset] = count
count += 1
for i in range(n-offset, starty, -1): # 从右至左, startx保持不变,starty递减
nums[n-offset][i] = count
count += 1
for i in range(n-offset, startx, -1): # 从下至上, starty保持不变,,startx递减
nums[i][starty] = count
count += 1
# 更新起点
startx += 1
starty += 1
if n%2 == 1: # n为奇数时,填充中心点
nums[mid][mid] = count
return nums
54. 中等
螺旋矩阵
题目:给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
例1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]例2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
待更……
边栏推荐
猜你喜欢
Modulo operation (MOD)
全面讲解 Handler机制原理解析 (小白必看)
电子组装行业对MES管理系统的需求分析
Tanabata festival coming, VR panoramic look god assists for you
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-中
【超详细教程】LVS+KeepAlived高可用部署实战应用
typescript53 - generic constraints
ASP.NET 获取数据库的数据并写入到excel表格中
Analysis of usage scenarios of mutex, read-write lock, spin lock, and atomic operation instructions xaddl and cmpxchg
typescript50-交叉类型和接口之间的类型说明
随机推荐
全面讲解 Handler机制原理解析 (小白必看)
LYVE1抗体丨Relia Tech LYVE1抗体解决方案
C # WPF equipment monitoring software (classic) - the next
Slipper —— 虚点,最短路
Analysis: What makes the Nomad Bridge hack unique
typescript50 - type specification between cross types and interfaces
typescript51-泛型的基本使用
中原银行实时风控体系建设实践
ML18-自然语言处理
Google Earth Engine - Calculates the effective width of rivers using publicly available river data
C 学生管理系统_分析
C语言 函数递归
Linux安装mysql最简单教程(一次成功)
Electronics manufacturing enterprise deployment WMS what are the benefits of warehouse management system
typescript57-数组泛型接口
优秀的测试/开发程序员,是怎样修炼的?步步为营地去执行......
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
Mvc, Mvp and Mvvm
咱们500万条数据测试一下,如何合理使用索引加速?
Nanoprobes Mono- Sulfo -NHS-Nanogold的使用和应用