40 lines
1.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* https://leetcode.cn/problems/rotate-image/?envType=study-plan-v2&envId=top-interview-150
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
const rotate = function (matrix) {
};
/**
* 思路:
* 1. 首先进行矩阵的转置操作:将 matrix[i][j] 和 matrix[j][i] 交换,遍历时确保 i < j避免重复交换。
* 2. 然后反转每一行,将每一行的元素顺序倒过来。
* 这两步操作完成后,矩阵就会被顺时针旋转 90 度。
*/
function f1(matrix) {
const n = matrix.length;
// 对矩阵装置
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
const tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
// 反转每一行
for (let i = 0; i < n; i++) {
let left = 0;
let right = n - 1;
while (left < right) {
const tmp = matrix[i][left];
matrix[i][left] = matrix[i][right];
matrix[i][right] = tmp;
left++;
right--;
}
}
}