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?
将二维数组顺时针旋转90度,原地(不占用与n有关系的空间大小)
手写两组n为4,5的二维数组转换前与转换后的结果,解出旋转后的结果,直接带入
len为n-1,原来位置为matrix[i][j]的元素,经过旋转后位置为matrix[j][len-i],每次旋转4个元素,并分n为奇偶两种情况划定旋转范围,得到结果
public class Solution {
public void rotate(int[][] matrix) {
int x,y;
if(matrix.length%2==1){
x=matrix.length/2;
y=x+1;
}else {
x=matrix.length/2;
y=x;
}
int len = matrix.length-1;
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
int temp = matrix[i][j];
matrix[i][j]=matrix[len-j][i];
matrix[len-j][i]=matrix[len-i][len-j];
matrix[len-i][len-j]=matrix[j][len-i];
matrix[j][len-i]=temp;
}
}
}
}