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?
Subscribe to see which companies asked this question
public void rotate(int[][] matrix) { if(matrix.length==1) return; int length=matrix.length; for(int i=0;i<=(length-1)/2;i++) { for(int j=i;j<length-1-i;j++) { int temp=matrix[i][j]; matrix[i][j]=matrix[length-1-j][i]; matrix[length-1-j][i]=matrix[length-1-i][length-1-j]; matrix[length-1-i][length-1-j]=matrix[j][length-1-i]; matrix[j][length-1-i]=temp; } } }可以看到i取值为<=(matix.length-1)/2 这个由旋转对称性很好理解,重点需要考虑j的取值,我是通过j=3,4,5,6....的规律找出来的