AC JAVA in place to rotate with one time loop


  • 0
    I

    rotate four numbers as a group.
    Let matrix[row][col] rotate to matrix[col][n - 1- row]

    /*
     * 1 2 3        1 2 1         1 2 1         1 2 1          7 2 1
     * 4 5 6   =>   4 5 6    =>   4 5 6    =>   4 5 6    =>    4 5 6 
     * 7 8 9        7 8 9         7 8 3         9 8 3          9 8 3
    */
    
    public void rotate(int[][] matrix) {
            if(matrix == null || matrix.length == 0) return;
            int n = matrix.length;
            for(int i = 0; i < n/2; i++) {
                for(int j = i; j < n-1-i; j++) {
                    int row = i;
                    int col = j;
                    int replace = matrix[row][col];
                    for(int count = 1; count <= 4; count++) {
                        int tempNum = matrix[col][n-1-row];
                        matrix[col][n-1-row] = replace;
                        replace = tempNum;
                        int tempRow = row;
                        row = col;
                        col = n - 1 - tempRow;
                    }
                }
            }
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.