题目地址:链接
题目描述: 给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
示例输出:
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
找规律
思路: (x, y) --> (y, n - 1 - x)
更加高效:转换为(x, y) --> (y, x) --> (y, n - 1 - x))经过转置和反转纵坐标即可实现
var rotate = function(matrix) {
let n = matrix.length;
for(let i = 0; i < n / 2; i ++) {
for(let j = 0; j < Math.floor(n / 2); j ++) {
let [tmpi, tmpj] = [i, j];
let tmp = matrix[i][j];
for(let k = 0; k < 4; k ++) {
let [li, lj] = [tmpj, n - 1 - tmpi];
[matrix[li][lj], tmp] = [tmp, matrix[li][lj]];
[tmpi, tmpj] = [li, lj];
}
}
}
};

8万+

被折叠的 条评论
为什么被折叠?



