leetcode 48

📌 一、任务背景
我们需要完成一个「原地」旋转二维矩阵 90° 的函数,即在不申请额外空间的前提下,对矩阵进行顺时针旋转。
🎯 二、战况分析(逐步拆解)
🔁 1. 层级推进机制
let top = 0, bottom = matrix.length - 1;
while (top < bottom)
我们通过双指针 top 和 bottom 控制当前处理的外层边界,随着每轮旋转推进,内层矩阵会逐步被旋转处理。
✅ 每轮循环对应处理一圈(layer)。
🔄 2. 单圈四点轮换
for (let i = top; i < bottom; i++) {// 每次处理一个四元组的旋转
}
在当前圈中,我们从 top 到 bottom,依次旋转边上的四个点,构成一个“角点旋转”的闭环。
📦 3. 四向角变换核心
我们以 4x4 矩阵为例,分析每一组四点如何轮换位置:
const temp = matrix[top][i]
matrix[top][i] = matrix[bottom - i + top][top]
matrix[bottom - i + top][top] = matrix[bottom][bottom - i + top]
matrix[bottom][bottom - i + top] = matrix[i][bottom]
matrix[i][bottom] = temp
假设我们当前处理如下矩阵的外圈:
1 2 3 4
5 8
9 12
13 14 15 16
某一次 i 的角变换顺序:
matrix[top][i] ← matrix[bottom - i + top][top]matrix[bottom - i + top][top] ← matrix[bottom][bottom - i + top]matrix[bottom][bottom - i + top] ← matrix[i][bottom]matrix[i][bottom] ← temp
这构成一个顺时针角点轮换,4 个角点依次完成交换,且不需额外空间。
📊 三、图示说明(逻辑可视化)
以 4x4 举例,原始矩阵如下:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
第一圈旋转变换如下(用箭头表示轮换顺序):
1 → 13 → 16 → 4 → 1
2 → 9 → 15 → 8 → 2
3 → 5 → 14 → 12 → 3
第二圈(中间层):
6 → 10 → 11 → 7 → 6
通过这样的轮换,矩阵即可原地顺时针旋转 90 度。
四、技术要点总结
- ✅ 使用双指针
top、bottom管理每层的上下边界。 - ✅ 每轮处理一圈中的所有角点组,每组做四次顺时针变换。
- ✅ 全程原地操作,无需额外数组空间。
- ✅ 时间复杂度:O(n²),空间复杂度:O(1)。
参考视频:https://www.bilibili.com/video/BV1FaHbecE9V/?spm_id_from=333.337.search-card.all.click&vd_source=ccb42000243a376a86b435878466ec00
实现
var rotate = function (matrix) {let top = 0, bottom = matrix.length - 1;while (top < bottom) {for (let i = top; i < bottom; i++) {// 第一次角变换const temp = matrix[top][i]matrix[top][i] = matrix[bottom - i + top][top]// // 第二次角变换matrix[bottom - i + top][top] = matrix[bottom][bottom - i + top]// // 第三次角变换matrix[bottom][bottom - i + top] = matrix[i][bottom]// // 第四次角变换matrix[i][bottom] = temp}top++bottom--}return matrix
}
📌 更多思考
- 能否改为先转置矩阵再左右镜像实现?
- 若矩阵不是正方形该如何处理?
- 若允许额外空间,有哪些更简单的实现方式?
欢迎在评论区交流你的看法 🙌
