题目描述:
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?
题目说了空间复杂度是O(1),那么就不能用n或者n*n的数组存储,只有一个点一个点的看,这道题关键是把第i行四个顶点的坐标找到,即(i,i,),(i,n-1+i),(n-1+i,i),(n-1+i,n-1+i).
代码如下:
public void rotate(int[][] matrix) {
int n=matrix.length;
for(int i=0;i<n/2;i++){
for (int j=0;j<n-2*i-1;j++) {
int temp=matrix[i][i+j];
matrix[i][i+j]=matrix[n-1-i-j][i];
matrix[n-1-i-j][i]=matrix[n-1-i][n-1-i-j];
matrix[n-1-i][n-1-i-j]=matrix[i+j][n-1-i];
matrix[i+j][n-1-i]=temp;
}
}
}