In space 0ms Java solution


  • 0
    C

    My solution just consider the nxn matrix into four blocks and swap them one by one.
    The boundary of the blocks varied when n is odd or even. And the for loop will swap th top left part to top right, top right part to bottom right and the bottom right part to bottom left.

    public class Solution {
    public void rotate(int[][] matrix) {
        int n=matrix.length;
        int q=0;
        int p=0;
        if(n%2==0)
        {
            p=n/2;
            q=n/2;
        }
        else
        {
            p=n/2;
            q=n/2+1;
        }
        for(int i=0; i<p; i++)
        {
            for(int j=0; j<q; j++)
            {
                int temp=matrix[j][n-i-1];
                matrix[j][n-i-1]=matrix[i][j];
                int temp2=matrix[n-i-1][n-j-1];
                matrix[n-i-1][n-j-1]=temp;
                int temp3=matrix[n-j-1][i];
                matrix[n-j-1][i]=temp2;
                matrix[i][j]=temp3;
            }
        }
    }
    

    }


Log in to reply
 

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