48. Rotate Image
source: https://leetcode.com/problems/rotate-image/
Question
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
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.
思路
顺时针旋转形象点想的话,就是去把原本矩阵的每行给立起来。
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function (matrix) {
const n = matrix.length;
const ret = [];
for (let x = 0; x < n; x++) ret.push([]);
for (let y = n - 1; y >= 0; y--) {
const line = matrix[y];
for (let x = 0; x < n; x++) {
ret[x][n - 1 - y] = line[x];
}
}
for (let x = 0; x < n; x++) matrix[x] = ret[x];
};
总结
对于这种题目要先多观察,总结规律然后开始写题,事半功倍。