Description
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:
1 | Given input matrix = |
Example 2:
1 | Given input matrix = |
解法
根据观察,可以首先对原数组取其转置矩阵,然后把每行的数字翻转可得到结果,如下所示:
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
注意转置的时候,或者翻转的时候不要重复交换位置。所以转置的时候j从i开始,而翻转的时候到中轴线停止翻转。
具体代码如下:
1 | class Solution { |