2
2
3
3
/**
4
4
* 48. Rotate Image
5
- *
6
- * You are given an n x n 2D matrix representing an image.
5
+
6
+ You are given an n x n 2D matrix representing an image.
7
7
8
8
Rotate the image by 90 degrees (clockwise).
9
9
10
- Follow up:
11
- Could you do this in-place?
10
+ Note:
11
+ You have to rotate the image in-place, which means you have to modify the
12
+ input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
13
+
14
+ Example 1:
15
+ Given input matrix =
16
+ [
17
+ [1,2,3],
18
+ [4,5,6],
19
+ [7,8,9]
20
+ ],
21
+ rotate the input matrix in-place such that it becomes:
22
+ [
23
+ [7,4,1],
24
+ [8,5,2],
25
+ [9,6,3]
26
+ ]
27
+
28
+ Example 2:
29
+ Given input matrix =
30
+ [
31
+ [ 5, 1, 9,11],
32
+ [ 2, 4, 8,10],
33
+ [13, 3, 6, 7],
34
+ [15,14,12,16]
35
+ ],
36
+ rotate the input matrix in-place such that it becomes:
37
+ [
38
+ [15,13, 2, 5],
39
+ [14, 3, 4, 1],
40
+ [12, 6, 8, 9],
41
+ [16, 7,10,11]
42
+ ]
12
43
*/
13
44
public class _48 {
14
45
@@ -22,7 +53,6 @@ public void rotate(int[][] matrix) {
22
53
* 1, 2, 3 1, 4, 7 7, 4, 1
23
54
* 4, 5, 6 becomes 2, 5, 8 becomes 8, 5, 2
24
55
* 7, 8, 9 3, 6, 9 9, 6, 3
25
- This is done in O(1) space!
26
56
**/
27
57
int m = matrix .length ;
28
58
for (int i = 0 ; i < m ; i ++) {
@@ -51,11 +81,13 @@ This is done in O(1) space!
51
81
52
82
public static class Solution2 {
53
83
/**First swap the rows bottom up, then swap the element on the diagonal:
84
+ *
54
85
* 1, 2, 3 7, 8, 9 7, 4, 1
55
86
* 4, 5, 6 becomes 4, 5, 6 becomes 8, 5, 2
56
87
* 7, 8, 9 1, 2, 3 9, 6, 3
57
88
*
58
- * This is using O(n) of extra space
89
+ * Time: O(n^2)
90
+ * Space: O(1)
59
91
*/
60
92
public void rotate (int [][] matrix ) {
61
93
int m = matrix .length ;
0 commit comments