有一个n x n整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。
给定一个n x n的矩阵,和矩阵的阶数n,请返回旋转后的n x n矩阵。
数据范围:0 < n <300,矩阵中的值满足 0≤val≤1000
要求:空间复杂度 O(n^2),时间复杂度 O(n^2)
进阶:空间复杂度 O(1),时间复杂度 O(n^2)
输入例子:
[[9,8,7],[6,5,4],[3,2,1]],3
输出例子:
[[3,6,9],[2,5,8],[1,4,7]]
采用for循环遍历矩阵,易知下标对换如下所示。
vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n)
{
vector<vector<int> > mat2 = mat;
for(int i = 0;i < n; i++){
for(int j = 0;j < n; j++){
mat2[j][n-1-i] = mat[i][j];
}
}
return mat2;
}
此时空间复杂度O(n^2),时间复杂度O(n^2)
采用轮换对称改进如下所示
class Solution {
public:
vector<vector<int> > rotateMatrix(vector<vector<int> >& mat, int n) {
// write code here
int i,j;
int temp;
for(i=0;i<n/2+1;i++){
for(j=0;j<n/2;j++){
temp=mat[i][j];
mat[i][j]=mat[n-1-j][i];
mat[n-1-j][i]=mat[n-1-i][n-1-j];
mat[n-1-i][n-1-j]=mat[j][n-1-i];
mat[j][n-1-i]=temp;
}
}
return mat;
}
};
此时空间复杂度O(1),时间复杂度O(n^2)