90°旋转二维数组
解法1: 先以对角线为轴翻转得到其转置矩阵,再以中间竖轴翻转。
1 2 3 1 4 7 7 4 1
4 5 6 --> 2 5 8 --> 8 5 2
7 8 9 3 6 9 9 6 3
解法2: 先以反对角线翻转,在以中间水平轴翻转。
1 2 3 9 6 3 7 4 1
4 5 6 --> 8 5 2 --> 8 5 2
7 8 9 7 4 1 9 6 3
使用第一种解法
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
// along the left top to right bottom diagonal line, swap symmetrical pair
for(int i=0; i<n; i++) { // for each row
for(int j=i+1; j<n; j++) { // for each number
// swap the pair
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// flip each row horizontally
for(int i=0; i<n; i++) {
for(int j=0; j<n/2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n-1-j];
matrix[i][n-1-j] = temp;
}
}
}
}