【题目描述】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?
【解题思路】首先对于将矩阵旋转90°,可以将比较旋转前后的坐标变换。对于原矩阵matrix[n][n],和旋转后得到的矩阵res[n][n],我们可以得到res[i][j]=matrix[n - j-1][i],根据该公式即可以求出旋转后的矩阵,空间、时间间复杂度均为O(n*n)。
【考查内容】数组
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int len = matrix.size();
vector<vector<int> >res;
vector<int >temp;
for (int i = 0; i < len; i++){
for (int j = 0; j < len; j++)
temp.push_back(matrix[len - j-1][i]);
res.push_back(temp);
temp.clear();
}
for (int i = 0; i < len; i++)
for (int j = 0; j < len; j++)
matrix[i][j] = res[i][j];
}
};