题目链接:https://leetcode-cn.com/problems/rotate-matrix-lcci/
题目描述
给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
不占用额外内存空间能否做到?
第一次编辑代码:
class Solution {
public void rotate(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int[][] result = new int[row][col];
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++){
result[i][j] = matrix[row - j -1][i];
}
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++){
matrix[i][j] = result[i][j];
}
}
}
提交结果
就这?
反思
为了节省空间,可以两次翻转。
第二次编辑代码:
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
//对角线翻转
for(int i = 0; i < n - 1; i++)
for(int j = i + 1; j < n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
//对称轴翻转
for(int i = 0; i < n; i++)
for(int j = 0; j < n/2; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 -j];
matrix[i][n - 1 -j] = temp;
}
}
}
提交结果