LeetCode面試題 01.07. 旋轉矩陣

面試題 01.07. 旋轉矩陣 題目鏈接

解題思路:順時針旋轉 90° 對應轉換規則 (x,y)->(y,n-x) ,n=N-1

public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length < 1) {
            return;
        }
        int n = matrix.length - 1;
        int[][] tempMatrix = new int[matrix.length][matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                tempMatrix[i][j] = matrix[n-j][i];
            }
        }
        for (int i = 0; i < matrix.length; i++) {
            matrix[i] = tempMatrix[i];
        }
    }

解法2:不借助輔助空間,先按對角線(右上角-左下角)對稱交換值,在上下對稱交換值

public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length < 1) {
            return;
        }
        int n = matrix.length - 1;
        // 對角線交換:(x,y)->(n-y,n-x)
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n - row; col++) {
                swap(matrix, row, col, n - col, n - row);
            }
        }
        // 上下交換:(x,y)->(n-x,n-y)
        for (int row = 0; row < matrix.length / 2; row++) {
            for (int col = 0; col < matrix.length; col++) {
                swap(matrix, row, col, n - row, col);
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章