当前位置:网站首页>[LeetCode] Summary of Matrix Simulation Related Topics
[LeetCode] Summary of Matrix Simulation Related Topics
2022-08-04 23:49:00 【Peter Pan China】
A summary of matrix simulation related topics
文章目录
写在前面
这里是小飞侠Pan🥳,立志成为一名优秀的前端程序媛!!!
本篇文章同时收录于我的github前端笔记仓库中,持续更新中,欢迎star~
https://github.com/mengqiuleo/myNote
59.螺旋矩阵 II
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
.
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
题解思路
The idea here is just transport,The original link is below
- 生成一个 n×n 空矩阵 dep,随后模拟整个向内环绕的填入过程:
- 定义当前左右上下边界 left,right,top,bottom,初始值 count,迭代终止值 total = n * n;
- 当 count < total 时,始终按照 从左到右 从上到下 从右到左 从下到上 填入顺序循环,每次填入后:
- 执行 ++count:得到下一个需要填入的数字;
- 更新边界:例如从左到右填完后,上边界 top ++,相当于上边界向内缩 1.
- 最终返回 mat 即可.
原文链接:Spiral Matrix II (模拟法,设定边界,代码简短清晰)
var generateMatrix = function(n) {
//四个边界
let left = 0;
let right = n - 1;
let bottom = n - 1;
let top = 0;
const total = n * n;//矩阵总数
const dep = [];//初始化矩阵
for(let i = 0; i < n; i++){
dep[i] = [];
}
let count = 0;
while(count < total){
for(let i = left; i <= right; i++) dep[top][i] = ++count;//从左到右
top++;
for(let i = top; i <= bottom; i++) dep[i][right] = ++count;//从上到下
right--;
for(let i = right; i >= left; i--) dep[bottom][i] = ++count;//从右到左
bottom--;
for(let i = bottom; i >= top; i--) dep[i][left] = ++count;//从下到上
left++;
}
return dep;
};
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]
题解思路
- When iterating over all items,res The array is constructed.我们可以用 res 数组的长度 等于 The number of entries in the matrix,作为循环的结束条件
- Does not mean to continue to traverse,等于就 break
举例说明
- 每遍历一条边,The starting point of the next edge traversal is “挤占”,To update the corresponding boundaries
- 注意到,Possibly in the loop,Suddenly the conditions of the loop are no longer satisfied,即top > bottom或left > right,其中一对边界彼此交错了
- This means that all items have been traversed,要break了,如果没有及时 break ,就会重复遍历
For the matrix on the left in the image above:
The four boundary values of the upper, lower, left and right are initialized respectively:
- top = 0, right = 5, bottom = 4, left = 0
When the outermost circle is traversed,The four boundary values are now :
- top = 1, right = 4, bottom = 3, left = 1
When the second traversal is completed,The four boundary values are now :
- top = 2, right = 3, bottom = 2, left = 2
At this point, it starts to traverse the middle two numbers: 15,16,After traversing from left to right,此时执行top++,那么此时 top=3.
If not end the loop,Then the next value will overwrite the value already assigned in the picture22
So the loop should be exited at this point
解决办法
- 每遍历完一条边,After updating the corresponding boundaries,都加上一句if (top > bottom || left > right) break;,Avoid repeated traversal due to not exiting the loop in time.
- 且,“遍历完成”这个时间点,Either happens at the end of the traversal“上边”,Either happens at the end of the traversal“右边”
- So just after these two steps,加 if (top > bottom || left > right) break 即可
var spiralOrder = function (matrix) {
if (matrix.length == 0) return []
const res = []
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
const size = matrix.length * matrix[0].length
while (res.length !== size) {
// The traversal is not over yet
for (let i = left; i <= right; i++) res.push(matrix[top][i])
top++
for (let i = top; i <= bottom; i++) res.push(matrix[i][right])
right--
if (res.length === size) break // 遍历结束
for (let i = right; i >= left; i--) res.push(matrix[bottom][i])
bottom--
for (let i = bottom; i >= top; i--) res.push(matrix[i][left])
left++
}
return res
};
剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字.
示例 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]
题解思路
- 这个题与54题类似
var spiralOrder = function(matrix) {
if(matrix.length === 0){
return [];
}
let res = [];
const total = matrix.length * matrix[0].length;
let top = 0, right = matrix[0].length - 1, bottom = matrix.length - 1, left = 0;
while(res.length !== total){
for(let i = left; i <= right; i++) res.push(matrix[top][i]);
top++;
for(let i = top; i <= bottom; i++) res.push(matrix[i][right]);
right--;
if(res.length === total) break;
for(let i = right; i >= left; i--) res.push(matrix[bottom][i]);
bottom--;
for(let i = bottom; i >= top; i--) res.push(matrix[i][left]);
left++;
}
return res;
};
48. 旋转图像
给定一个 n × n 的二维矩阵 matrix 表示一个图像.请你将图像顺时针旋转 90 度.
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵.请不要 使用另一个矩阵来旋转图像.
题解思路
作为例子,先将其通过水平轴翻转得到:
再根据主对角线翻转得到:
就得到了答案.这是为什么呢?对于水平轴翻转而言,We just need to enumerate the elements in the upper half of the matrix,Swap with the elements in the lower half,即
var rotate = function(matrix) {
const n = matrix.length;
//水平中轴线翻转
for(let i = 0; i < Math.floor(n/2); i++){
for(let j = 0; j < n; j++){
[matrix[i][j], matrix[n - i - 1][j]] = [matrix[n - i - 1][j], matrix[i][j]];
}
}
//主对角线翻转
for(let i = 0; i < n; i++){
for(let j = 0; j < i; j++){
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
};
There are other topics similar to this one:面试题 01.07. 旋转矩阵
做法相同,在这里不再赘述\
566. 重塑矩阵
在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据.
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数.
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充.
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵.
题解思路
- Convert the original two-dimensional array to one-dimensional
- Then judge whether the length matches
- Fill at the end
var matrixReshape = function(mat, r, c) {
const newMat = [];
//将二维数组转换为一维数组
for(let i = 0; i < mat.length; i++){
newMat.push(...mat[i]);
}
//Determine whether the length meets the requirements
if(r * c !== newMat.length) return mat;
//重塑矩阵
for(let i = 0; i < r; i++){
const item = [];
//每行c个
for(let j = 0; j < c; j++){
//将c个元素从头部拿出,并放入暂存的item数组
item.push(newMat.shift());
}
//当前行收集完毕,Push to the end of the new array
newMat.push(item);
}
return newMat;
};
注意:JS There is no concept of a two-dimensional array in ,You need to create a two-dimensional array object yourself
首先JSThe way to create a 2D array is not straightforwardnew Array[][],
而是要先new一个一维数组,Then put each element of this one-dimensional array new 为一个数组
const dep = [];//初始化矩阵
for(let i = 0; i < n; i++){
dep[i] = [];
}
Or write each row as an array,Refer to this topic for specific code
边栏推荐
- #yyds干货盘点#交换设备丢包严重的故障处理
- [Cultivation of internal skills of string functions] strncpy + strncat + strncmp (2)
- 【LeetCode】双指针题解汇总
- First, the basic concept of reptiles
- kernel hung_task死锁检测机制原理实现
- Statistical words (DAY 101) Huazhong University of Science and Technology postgraduate examination questions
- 手写分布式配置中心(1)
- Day118. Shangyitong: order list, details, payment
- KT6368A Bluetooth certification problem_FCC and BQB_CE_KC certification or other instructions
- 2022 Niu Ke Summer Multi-School Training Camp 5 (BCDFGHK)
猜你喜欢
SQL association table update
VMware NSX 4.0 -- 网络安全虚拟化平台
KT148A语音芯片ic工作原理以及芯片的内部架构描述
Security software Avast and Symantec NortonLifeLock merge with UK approval, market value soars 43%
【手撕AHB-APB Bridge】~ AMBA总线 之 AHB
年薪50W+的测试工程师都在用这个:Jmeter 脚本开发之——扩展函数
kernel hung_task死锁检测机制原理实现
[CVA Valuation Training Camp] Financial Modeling Guide - Lecture 1
小黑leetcode冲浪:94. 二叉树的中序遍历
MySQL基础篇【子查询】
随机推荐
2022年华数杯数学建模
uniapp动态实现滑动导航效果demo(整理)
【CVA估值训练营】财务建模指南——第一讲
三、实战---爬取百度指定词条所对应的结果页面(一个简单的页面采集器)
jenkins发送邮件系统配置
Kernel函数解析之kernel_restart
web3.js
Day118. Shangyitong: order list, details, payment
Flutter启动流程(Skia引擎)介绍与使用
C语言实现扫雷 附带源代码
DNS常见资源记录类型详解
ClickHouse 二级索引
uniapp横向选项卡(水平滚动导航栏)效果demo(整理)
MySQL增删改查基础
mysql基础
入门3D游戏建模师知识必备
Mathematical Principles of Matrix
Basic web in PLSQL
七牛云图片上传
The market value of 360 has evaporated by 390 billion in four years. Can government and enterprise security save lives?