48. Rotate Image
Last updated
Last updated
/**
* Time complexity : O(N*N)
* Space complexity : O(1)
*/
class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length == 0) return;
int row = matrix.length,
col = matrix.length;
// trnspose of a matrix
for(int r = 0; r < row; r++) {
for(int c = r+1; c < col; c++) {
int tmp = matrix[r][c];
matrix[r][c] = matrix[c][r];
matrix[c][r] = tmp;
}
}
// swap columns
for(int c = 0; c < col/2; c++) {
for(int r = 0; r < row; r++) {
int tmp = matrix[r][c];
matrix[r][c] = matrix[r][col-c-1];
matrix[r][col-c-1] = tmp;
}
}
}
}/**
* Time complexity : O(N*N)
* Space complexity : O(1)
*/
class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length <= 1) return;
int n = matrix.length;
for(int layer = 0; layer < n/2; layer++) {
for(int i = layer; i < n-layer-1; i++) {
int tmp = matrix[layer][i];
matrix[layer][i] = matrix[n-i-1][layer];
matrix[n-i-1][layer] = matrix[n-layer-1][n-i-1];
matrix[n-layer-1][n-i-1] = matrix[i][n-layer-1];
matrix[i][n-layer-1] = tmp;
}
}
}
}