Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
题意:给定一个n*n二维数组,将其旋转90度。
你能在原地操作吗?
分类:数组
解法1:如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。
public class Solution { public void rotate(int[][] matrix) { int n = matrix.length; int[][] res = new int[n][n]; for(int i=0;i<n-1;i++){ for(int j=0;j<n-i;j++){ swap(matrix,i,j,n-1-j,n-1-i); } } for(int i=0;i<n/2;i++){ for(int j=0;j<n;j++){ swap(matrix,i,j,n-i-1,j); } } } public void swap(int[][] matrix,int x1,int y1,int x2,int y2){ int t = matrix[x1][y1]; matrix[x1][y1] = matrix[x2][y2]; matrix[x2][y2] = t; } }
public class Solution { public void rotate(int[][] matrix) { int n = matrix.length; int[][] res = new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ res[j][n-i-1] = matrix[i][j]; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ matrix[i][j] = res[i][j]; } } } }