leetcode 链接:48. 旋转图像
题目
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
示例:![[中等] 48. 旋转图像 - 图1](/uploads/projects/xf015y@ivbwyo/bfd2d18c4159810e43e9a55701a4808a.jpeg)
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]输出:[[7,4,1],[8,5,2],[9,6,3]]
解答 & 代码
沿主对角线翻转+沿纵向中轴线翻转
1 2 3 1 4 7 7 4 1
4 5 6 --沿主对角线翻转--> 2 5 8 --沿纵向中轴线翻转--> 8 5 2
7 8 9 3 6 9 9 6 3
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int len = matrix.size();
// 先沿主对角线翻转
for(int row = 0; row < len; ++row)
{
for(int col = row + 1; col < len; ++col)
{
int temp = matrix[row][col];
matrix[row][col] = matrix[col][row];
matrix[col][row] = temp;
}
}
// 再沿纵向中轴线翻转
for(int row = 0; row < len; ++row)
{
int left = 0;
int right = len - 1;
while(left < right)
{
int temp = matrix[row][left];
matrix[row][left] = matrix[row][right];
matrix[row][right] = temp;
++left;
--right;
}
}
}
};
执行结果:
执行结果:通过
执行用时:4 ms, 在所有 C++ 提交中击败了 43.66% 的用户
内存消耗:6.9 MB, 在所有 C++ 提交中击败了 50.25% 的用户
