当前位置:网站首页>螺旋矩阵_数组 | 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]
待更……
边栏推荐
- 无代码7月热讯 | 微软首推数字联络中心平台;全球黑客马拉松...
- Vant3 - click on the corresponding name name to jump to the next page corresponding to the location of the name of the TAB bar
- C 学生管理系统_分析
- Electronics manufacturing enterprise deployment WMS what are the benefits of warehouse management system
- 【超详细】手把手教你搭建MongoDB集群搭建
- typescript53 - generic constraints
- typescript48-函数之间的类型兼容性
- 动态内存二
- 静态文件快速建站
- typescript51 - basic use of generics
猜你喜欢
随机推荐
600MHz频段来了,它会是新的黄金频段吗?
BGP实验(含MPLS)
GeoAO:一种快速的环境光遮蔽方案
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-中
【性能优化】MySQL性能优化之存储引擎调优
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
typescript56-泛型接口
Tanabata festival coming, VR panoramic look god assists for you
【面经】被虐了之后,我翻烂了equals源码,总结如下
【日志框架】
C语言 函数递归
网络带宽监控,带宽监控工具哪个好
《Greenplum构建实时数据仓库实践》简介
Mvc, Mvp and Mvvm
How to find the cause of Fiori Launchpad routing errors by single-step debugging
MATLAB三维绘图命令plot3入门
jmeter分布式压测
机器学习——库
Google Earth Engine - Calculates the effective width of rivers using publicly available river data















