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?
Solution:O(n^2)
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0
|| matrix.length != matrix[0].length)
return;
int rowcount = matrix.length;
int s = rowcount -1;
for (int i = 0; i < rowcount / 2; i++) {
for (int j = i; j < rowcount - i-1; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[s-j][i];
matrix[s-j][i] = matrix[s-i][s-j];
matrix[s-i][s-j] = matrix[j][s-i];
matrix[j][s-i] = tmp;
}
}
}
}
沒有留言:
張貼留言