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為偶數(shù)時舔箭,i,j的范圍相同;
當n為奇數(shù)時悼枢,i比j最大值大1,則中線上的值只變動一次考榨,避免產(chǎn)生沖突继阻。(或者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;
}
}
}
}