LeetCode 48.
Tags: LeetCode
Complexity
-
Time complexity: O(n^2)
-
Space complexity: O(n)
Code
class Solution {
public void rotate(int[][] matrix) {
int layer = 0;
int n = matrix.length;
int value = 0;
int[] values = new int[n];
while (layer < n/2) {
for (int i=layer; i<n-1-layer; i++) { //top to right
values[i] = matrix[i][n-1-layer];
matrix[i][n-1-layer] = matrix[layer][i];
}
for (int i=layer; i<n-1-layer; i++) {//right to bottom
value = values[i];
values[i] = matrix[n-1-layer][n-1-i];
matrix[n-1-layer][n-1-i] = value;
}
for (int i=layer; i<n-1-layer; i++) {//bottom to left
value = values[i];
values[i] = matrix[n-1-i][layer];
matrix[n-1-i][layer] = value;
}
for (int i=layer; i<n-1-layer; i++) {//left to top
value = values[i];
matrix[layer][i] = value;
}
layer++;
}
}
}
Check out the description of this problem at LC 48.