https://leetcode.com/problems/rotate-image/
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?
注意画个图把这些下标都写出来,不然非常容易乱。
代码如下:
public void rotate(int[][] matrix) {
if(matrix==null || matrix.length==0) return;
int size = matrix.length;
int layer = size/2;
for(int i=0; i<layer; i++){
for(int j=i; j<(size-i-1); j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[size-j-1][i];
matrix[size-j-1][i] = matrix[size-i-1][size-j-1];
matrix[size-i-1][size-j-1] = matrix[j][size-i-1];
matrix[j][size-i-1] = tmp;
}
}
}
空间复杂度O(1),时间复杂度O(n^2)