Voyz's Studio.

LeetCode算法笔记--旋转图像

字数统计: 222阅读时长: 1 min
2020/12/13 Share

LeetCode算法笔记–Day40

48. Rotate Image

题目:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

example
input: input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
output: [
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

Analyze:

方法一:分层旋转

ab4d64994f3b7b174eef572ff596728f142cceb51beae3679f0c8e230342b521-image.png

58c76a0a3b1fed08f9546aa0993c99f3d1fff08a63987c960a5ccf23f7c71678-image.png

My Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
let _len = matrix.length,
_pointA=0,
_pointB=_len-1
// 从外向内圈层递进
while(_pointA < _pointB){
let _add = 0;
// 交换每四个元素
while(_pointA+_add < _pointB){
let _tmpArr = [matrix[_pointA][_pointA+_add],matrix[_pointA+_add][_pointB],matrix[_pointB][_pointB-_add],matrix[_pointB-_add][_pointA]];
matrix[_pointA][_pointA+_add] = _tmpArr[3];
matrix[_pointA+_add][_pointB] = _tmpArr[0];
matrix[_pointB][_pointB-_add] = _tmpArr[1];
matrix[_pointB-_add][_pointA] = _tmpArr[2];
_add += 1;
}
_pointA += 1;
_pointB -= 1;
}
return matrix;
};}
}
CATALOG
  1. 1. LeetCode算法笔记–Day40
  2. 2. 48. Rotate Image
    1. 2.1. 题目:
    2. 2.2. Analyze:
      1. 2.2.1. 方法一:分层旋转
    3. 2.3. My Answer: