48. Rotate Image
2026/1/12大约 2 分钟约 529 字
48. Rotate Image
难度: Medium
题目描述
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.
Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:

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]]
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000
解题思路
代码实现
解决方案
java
class Solution {
public void rotate(int[][] matrix) {
verticalMirrorInPlace(matrix);
transposeInPlace(matrix);
}
public static void transposeInPlace(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
int n = matrix.length;
// 遍历上三角区域(i < j),交换 matrix[i][j] 和 matrix[j][i]
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // j 从 i+1 开始,避免重复交换
// 交换元素
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
public static void verticalMirrorInPlace(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
int n = matrix.length;
// 遍历前 n/2 行,与对称行交换
for (int i = 0; i < n / 2; i++) {
int mirrorRow = n - 1 - i; // 对称行索引
// 逐元素交换第 i 行和第 mirrorRow 行
for (int j = 0; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[mirrorRow][j];
matrix[mirrorRow][j] = temp;
}
}
}
// 原地水平镜像(左右翻转)n×n 方阵
public static void horizontalMirrorInPlace(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
int n = matrix.length;
// 遍历每一行
for (int i = 0; i < n; i++) {
// 遍历每行的前 n/2 个元素,与对称位置交换
for (int j = 0; j < n / 2; j++) {
int mirrorCol = n - 1 - j; // 对称列索引
// 交换第 i 行的第 j 个和第 mirrorCol 个元素
int temp = matrix[i][j];
matrix[i][j] = matrix[i][mirrorCol];
matrix[i][mirrorCol] = temp;
}
}
}
}