48. Rotate Image
problem 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:
Example 2:
algorithm thought
最简单的方法肯定是定义一个矩阵,然后将这个矩阵转置之后赋值给这个矩阵。但是这样需要O(n²)空间题目也明显要求了我们空间复杂度维持在O(1)内。我们必须在本来的数组上操作。如果只能这么操作的话,肯定就是使用swap函数,交换值。我们可以对称的改变矩阵,对于旋转90度,我们只需要首先按照竖直中线对称,再按照对角线对称就能得到结果。
code
algorithm analysis
对二维矩阵操作,双重循环。最后时间复杂度是O(n²)
Last updated