LeetCode-48-旋转图像
in LeetCode with 0 comment

LeetCode-48-旋转图像

in LeetCode with 0 comment

原题地址:旋转图像

给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明:

你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

示例 2:

给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

先转置再逐行反转

先将矩阵转置(即将矩阵的行列互换),再逐行反转即可:

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
const rotate1 = function(matrix) {
    let n = matrix.length;
    // 先进行矩阵转置
    for (let i = 0; i < n; i ++) {
        for (let j = i + 1; j < n; j ++) {
            [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]
        }
    }
    // 每一行反转
    for (let i = 0; i < n; i ++) {
        for (let j = 0; j < Math.floor(n / 2); j ++) {
            [matrix[i][j], matrix[i][n-j-1]] = [matrix[i][n-j-1], matrix[i][j]];
        }
    }
};

测试:

let start = new Date();
const test = rotate1;
let matrix = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
];
test(matrix);
console.log(matrix); // [ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]
matrix = [
    [ 5, 1, 9,11],
    [ 2, 4, 8,10],
    [13, 3, 6, 7],
    [15,14,12,16]
];
test(matrix);
/**
 [
     [ 15, 13, 2, 5 ],
     [ 14, 3, 4, 1 ],
     [ 12, 6, 8, 9 ],
     [ 16, 7, 10, 11 ]
 ]
 */
console.log(matrix);
console.log(new Date().getTime() - start.getTime()); // 10

时间复杂度: 矩阵转置的时间复杂度为$O(N!)$,逐行反转的时间复杂度为$O( \frac{N^2}{2})$,总时间复杂度为$O(N^2)$
空间复杂度: 原地操作,空间复杂度为$O(1)$