My Java Solution with O(1) Space Complexity


  • 0
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int row=0; row<n/2; row++) {
            for(int col=row; col<n-1-row; col++) {
                int tmp = matrix[row][col];                      
                matrix[row][col] = matrix[n-1-col][row];
                matrix[n-1-col][row] = matrix[n-1-row][n-1-col];    
                matrix[n-1-row][n-1-col] = matrix[col][n-1-row];    
                matrix[col][n-1-row] = tmp;
            }
        }
    }
    

    Main Idea:

    matrix[row][col] left-top
    matrix[col][n-1-row] right-top
    matrix[n-1-row][n-1-col] right-bottom
    matrix[n-1-col][row] left-bottom

Log in to reply
 

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