当前位置:网站首页>[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
边栏推荐
猜你喜欢

一、爬虫基本概念

MySQL的安装与卸载

Privacy Computing Overview

游戏3D建模入门,有哪些建模软件可以选择?

3年,从3K涨薪到20k?真是麻雀啄了牛屁股 — 雀食牛逼呀
![[Happy Qixi Festival] How does Nacos realize the service registration function?](/img/df/5793145da45bc80d227b0babfac914.png)
[Happy Qixi Festival] How does Nacos realize the service registration function?

jenkins发送邮件系统配置

First, the basic concept of reptiles

MongoDB permission verification is turned on and mongoose database configuration

C5750X7R2E105K230KA(电容器)MSP430F5249IRGCR微控制器资料
随机推荐
Privacy Computing Overview
Basic web in PLSQL
PID Controller Improvement Notes No. 7: Improve the anti-overshoot setting of the PID controller
Nuclei (2) Advanced - In-depth understanding of workflows, Matchers and Extractors
吐槽 | 参加IT培训的正确姿势
C5750X7R2E105K230KA(电容器)MSP430F5249IRGCR微控制器资料
uniapp horizontal tab (horizontal scrolling navigation bar) effect demo (organization)
DNS常见资源记录类型详解
【七夕快乐篇】Nacos是如何实现服务注册功能的?
KT148A语音芯片ic工作原理以及芯片的内部架构描述
生产者消费者问题
Mathematical Principles of Matrix
Laravel 实现redis分布式锁
uniapp 分享功能-分享给朋友群聊朋友圈效果(整理)
Xiaohei leetcode surfing: 94. Inorder traversal of binary tree
MySQL基础篇【子查询】
npm基本操作及命令详解
【LeetCode】矩阵模拟相关题目汇总
mysql基础
头脑风暴:完全背包