题目:
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?
题解:
这道题就是考察很直白的旋转坐标。要in place的。画个图自己算算就出来了。
代码如下:
1 /* public void rotate(int[][] matrix) {
2 int m = matrix.length;
3 int n = matrix[0].length;
4
5 int[][] result = new int[m][n];
6
7 for(int i = 0; i<m; i++){
8 for(int j = 0; j<n; j++){
9 result[j][m-1-i] = matrix[i][j];
}
}
for(int i=0;i<m;i++){
for(int j=0; j<n; j++){
matrix[i][j] = result[i][j];
}
}
}
*/
//in place
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n-1-j][i];
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
matrix[j][n-1-i] = temp;
}
}