题目:
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?
public class Solution {
public void rotate(int[][] matrix) {
if(null==matrix||matrix.length<=0) return;
int x1=0, y1=0;
int n=matrix.length;
int x2=n-1, y2=n-1;
while(x1<x2&&y1<y2){
for(int i=x1,j=y1;j<y2;j++){
int temp = matrix[i][j];
matrix[i][j]=matrix[n-j-1][i];
matrix[n-j-1][i]=matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1]=matrix[j][n-i-1];
matrix[j][n-i-1]=temp;
}
x1++;y1++;
x2--;y2--;
}
}
}
参考:
本文介绍了一个二维矩阵旋转算法,该算法能够将一个 n x n 的矩阵顺时针旋转90度,并且实现了原地旋转,避免了额外的空间开销。
745

被折叠的 条评论
为什么被折叠?



