You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Could you do this in-place?
/*
First reverse up to down, then swap the symmetry.
time:O(n^2), space:O(1)
*/
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return;
}
if (matrix[0] == null || matrix[0].length == 0) {
return;
}
int m = matrix.length;
int n = matrix[0].length;
for (int i = 0; i < m / 2; i++) {
for (int j = 0; j < n; j++) {
swap(matrix, i, j, m - 1 - i, j);
}
}
for (int i = 0; i < m; i++) {
for (int j = i; j < n; j++) {
swap(matrix, i, j, j, i);
}
}
}
public void swap(int[][] matrix, int a, int b, int c, int d) {
int tmp = matrix[a][b];
matrix[a][b] = matrix[c][d];
matrix[c][d] = tmp;
}
}
No comments:
Post a Comment