天天看点

[leetCode]面试题 01.07. 旋转矩阵辅助数组原地旋转

[leetCode]面试题 01.07. 旋转矩阵辅助数组原地旋转

辅助数组

将旋转结果放入辅助数组,再将辅助数组得到的结果复制到matrix指向的内存空间。

原数组中的元素

matrix[row][col]

旋转之后变为

matrix[col][n- row -1]

class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        int[][] newMatrix = new int[n][n];
        for(int row = 0; row < n; row++){
            for(int col = 0; col < n; col++){
                newMatrix[col][n - row - 1] = matrix[row][col];
            }
        }
        //深拷贝
        for(int i = 0; i < n; i++){
            matrix[i] = newMatrix[i].clone();
        }
    }
}
           

原地旋转

只需水平翻转一次,再对角线翻转一次即可完成旋转90°

class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        //先水平翻转
        for(int row = 0; row < n/2; ++row){
            for(int col = 0; col < n; ++col){
                int temp = matrix[row][col];
                matrix[row][col] = matrix[n - row - 1][col];
                matrix[n - row - 1][col] = temp;
            }
        }
        //再对角线反转
        for(int row = 0; row < n; ++row){
            for(int col = 0; col < row; ++col){
                int temp = matrix[row][col];
                matrix[row][col] = matrix[col][row];
                matrix[col][row] = temp;
            }
        }
    }
}