Skip to content

Commit 02d722d

Browse files
committed
O(n^2) time and O(1) space using transpose and reverse double pass.
1 parent f2a7a1d commit 02d722d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Diff for: 48. Rotate Image/48. Rotate Image.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
You are given an n x n 2D matrix representing an image.
3+
4+
Rotate the image by 90 degrees (clockwise).
5+
6+
Note:
7+
8+
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.
9+
10+
Example 1:
11+
12+
Given input matrix =
13+
[
14+
[1,2,3],
15+
[4,5,6],
16+
[7,8,9]
17+
],
18+
19+
rotate the input matrix in-place such that it becomes:
20+
[
21+
[7,4,1],
22+
[8,5,2],
23+
[9,6,3]
24+
]
25+
Example 2:
26+
27+
Given input matrix =
28+
[
29+
[ 5, 1, 9,11],
30+
[ 2, 4, 8,10],
31+
[13, 3, 6, 7],
32+
[15,14,12,16]
33+
],
34+
35+
rotate the input matrix in-place such that it becomes:
36+
[
37+
[15,13, 2, 5],
38+
[14, 3, 4, 1],
39+
[12, 6, 8, 9],
40+
[16, 7,10,11]
41+
]
42+
"""
43+
44+
45+
class Solution:
46+
def rotate(self, matrix: List[List[int]]) -> None:
47+
"""
48+
Do not return anything, modify matrix in-place instead.
49+
"""
50+
for i in range(len(matrix)):
51+
for j in range(i, len(matrix)):
52+
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
53+
for i in range(len(matrix)):
54+
matrix[i].reverse()
55+

0 commit comments

Comments
 (0)