You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Subscribe to see which companies asked this question
分析:
找规律的题。
先沿着对角线(左上到右下)做对称变换,然后沿着竖直中心轴做对称变换。
ac代码:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int i,j,n=matrix.size(),k;
for(i=0;i<n;i++)
for(j=0;j<i;j++)
swap(matrix[i][j],matrix[j][i]);
for(i=0,j=n-1;i<j;i++,j--)
for(k=0;k<n;k++)
swap(matrix[k][i],matrix[k][j]);
}
};
本文介绍了一种用于将n x n的二维矩阵顺时针旋转90度的有效算法,并且能够实现就地(in-place)旋转,避免了额外的空间开销。通过两次对称变换实现了这一目标:首先沿主对角线进行一次对称变换,随后再沿垂直中轴线进行另一次对称变换。
2166

被折叠的 条评论
为什么被折叠?



