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?
一刷
题解:
坐标的变换为:
(i, j)->(j, n-1-i)->(n-1-i, n-1-j)->(n-1-j, i)->(i, j)
此时,注意i和j的范围
当n为偶数时,i,j的范围相同;
当n为奇数时,i比j最大值大1,则中线上的值只变动一次,避免产生冲突。(或者j比i最大值大1)
public class Solution {
public void rotate(int[][] matrix) {
//(i, j)->(j, n-1-i)->(n-1-i, n-1-j)->(n-1-j, i)->(i, j)
int n=matrix.length;
if(matrix == null) return;
for(int i=0; i<(n+1)/2; i++){
for(int j=0; j<n/2; j++){
int a = 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] = matrix[i][j];
matrix[i][j] = a;
}
}
}
}