|
4 | 4 |
|
5 | 5 | public class _48 {
|
6 | 6 |
|
7 |
| - /**Note: this is an n*n matrix, in other words, it's a square, this makes it easier as well.*/ |
| 7 | + /** |
| 8 | + * Note: this is an n*n matrix, in other words, it's a square, this makes it easier as well. |
| 9 | + */ |
8 | 10 |
|
9 | 11 | public static class Solution1 {
|
10 | 12 | //Time: O(n^2)
|
@@ -42,12 +44,13 @@ public void rotate(int[][] matrix) {
|
42 | 44 | }
|
43 | 45 |
|
44 | 46 | public static class Solution2 {
|
45 |
| - /**First swap the rows bottom up, then swap the element on the diagonal: |
46 |
| - * |
| 47 | + /** |
| 48 | + * First swap the rows bottom up, then swap the element on the diagonal: |
| 49 | + * <p> |
47 | 50 | * 1, 2, 3 7, 8, 9 7, 4, 1
|
48 | 51 | * 4, 5, 6 becomes 4, 5, 6 becomes 8, 5, 2
|
49 | 52 | * 7, 8, 9 1, 2, 3 9, 6, 3
|
50 |
| - * |
| 53 | + * <p> |
51 | 54 | * Time: O(n^2)
|
52 | 55 | * Space: O(1)
|
53 | 56 | */
|
@@ -75,23 +78,43 @@ public void rotate(int[][] matrix) {
|
75 | 78 | }
|
76 | 79 |
|
77 | 80 | public static class Solution3 {
|
| 81 | + /** |
| 82 | + * You only need to rotate the top right quarter, |
| 83 | + * with this example: |
| 84 | + * {1, 2, 3, 4}, |
| 85 | + * {5, 6, 7, 8}, |
| 86 | + * {9, 10, 11, 12}, |
| 87 | + * {13, 14, 15, 16} |
| 88 | + * |
| 89 | + * top will only be: |
| 90 | + * 1, 2, 3, |
| 91 | + * 6 |
| 92 | + * |
| 93 | + * then this entire matrix is rotated. As they'll drive to ratate the corresponding three elements in the matrix. |
| 94 | + * |
| 95 | + * Another cool trick that this solution takes advantage is that because it's a square matrix, |
| 96 | + * meaning number of rows equals to the number of columns, we could do swap like this, |
| 97 | + * if it's a rectangular, below method won't work and will throw ArrayIndexOutOfBoundsException. |
| 98 | + * |
| 99 | + */ |
78 | 100 | public void rotate(int[][] matrix) {
|
79 | 101 | int n = matrix.length;
|
80 | 102 | for (int i = 0; i < n / 2; i++) {
|
81 | 103 | for (int j = i; j < n - i - 1; j++) {
|
82 |
| - //save the top |
| 104 | + //save the top left |
83 | 105 | int top = matrix[i][j];
|
| 106 | + System.out.println("top = " + top); |
84 | 107 |
|
85 |
| - //move left to top |
| 108 | + //move bottom left to top left |
86 | 109 | matrix[i][j] = matrix[n - 1 - j][i];
|
87 | 110 |
|
88 |
| - //move bottom to left |
| 111 | + //move bottom right to bottom left |
89 | 112 | matrix[n - 1 - j][i] = matrix[n - i - 1][n - 1 - j];
|
90 | 113 |
|
91 |
| - //move right to bottom |
| 114 | + //move top right to bottom right |
92 | 115 | matrix[n - i - 1][n - 1 - j] = matrix[j][n - i - 1];
|
93 | 116 |
|
94 |
| - //move top to right |
| 117 | + //move top left to top right |
95 | 118 | matrix[j][n - i - 1] = top;
|
96 | 119 | }
|
97 | 120 | }
|
|
0 commit comments