1:38

LeetCode Hot 100:旋转图像

本期讲 LeetCode Hot 100 的「旋转图像」。题目给出一个 n × n 矩阵,要求把它顺时针旋转 90 度,并且必须直接修改原矩阵,不能使用另一个矩阵。1 这道题收录于 LeetCode 热题 100
关键转化是两步:先沿主对角线转置,让 (i, j) 变成 (j, i);再把每一行左右翻转,让列坐标变成 n - 1 - i。两次原地操作合起来,元素正好落到顺时针旋转后的坐标 (j, n - 1 - i)
function rotate(matrix) {
  const 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 (const row of matrix) {
    row.reverse();
  }
}
转置和逐行翻转都会访问 O(n²) 个元素,所以时间复杂度是 O(n²);交换过程只使用常数个临时变量,空间复杂度是 O(1)

References

  1. 1

This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.

Related content