题目:
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 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
提示:该矩阵为对称正方阵,操作只能在原矩阵上进行,不能另外开辟矩阵空间。
分析:(时间复杂度(O(2N^2)))
class Solution {
public void rotate(int[][] matrix) {
//顺时针旋转90度,在原矩阵的基础上操作,不使用新的矩阵
//解法:先竖着中间对折一次,之后逆对角线对折一次即可。
//矩阵为n*n的正方矩阵
int row=matrix.length;
int col=row;
//1.竖中间对折
//竖中间对折,只需要进行一半即可
int ax=(col+1)/2;//对称轴
for(int i=0;i<row;i++){
for(int j=0;j<ax;j++){
int temp=matrix[i][j];
matrix[i][j]=matrix[i][row-1-j];
matrix[i][row-1-j]=temp;
}
}
//2.逆对角线对折
//只需计算沿逆对角线一半
for(int i=0;i<row;i++){
for(int j=row-1-i;j>=0;j--){
//对称点(row-1-j,j)或者(i,row-1-i)
int temp=matrix[i][j];
matrix[i][j]=matrix[i+(row-1-i-j)][row-1-i];
matrix[i+(row-1-i-j)][row-1-i]=temp;
}
}
}
}
推荐算法时间复杂度(O(N^2)):
class Solution {
public void rotate(int[][] matrix) {
//顺时针旋转矩阵90度
//思路:采用上下左右四个点分别交换位置
//从内向外或者从外向内进行
if(matrix==null||matrix.length==0) return ;
int len=matrix.length;
for(int i=(len-1)/2;i>=0;i--){
for(int j=i;j<len-i-1;j++){
//采用从内往外
//上和右交换
swap(matrix,i,j,j,len-i-1);
//下和上交换
swap(matrix,i,j,len-i-1,len-j-1);
//左和下交换
swap(matrix,i,j,len-j-1,i);
}
}
}
public void swap(int [][]matrix,int i ,int j,int x,int y){
int temp=matrix[i][j];
matrix[i][j]=matrix[x][y];
matrix[x][y]=temp;
}
}