48_Rotate Image
Last updated
Was this helpful?
Last updated
Was this helpful?
You are given an nxn
2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image , 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:
If there is no constraint of in-place rotation, a brute force method is to initiate a new nxn
matrix and put each row in the original matrix into the column of the new matrix in a reversed order.
Idea: (In-place rotation)
split the whole matrix into 4 parts: upper-left, upper-right, bottom-right, bottom-left, loop over all the elements in the upper left part, and rotate the corresponding 3 elements in the other 3 parts.
Note that [~i]
means [n-1-i],
and it's easier to read.
Time Complexity:
Space Complexity:
Reference: