Simple in-place java solution with explanation


  • 0
    1. For any element in the array, after the rotation, a[i][j]-->a[j][n-1-i], a[j][n-1-i]-->a[n-1-i][n-1-j], a[n-1-i][n-1-j]-->a[n-1-j][i], a[n-1-j][i]-->a[i][j]
    2. So, every such four elements form a group. Hence we can do the rotation by dealing with total N*N/4 groups.
    3. In the loop, "i<(l+1)/2" and "j<l/2" can also be written as "i<l/2" and "j<(l+1)/2". The purpose is to make sure the N*N/4 groups exactly cover the whole array, no matter the size of array is odd or even.
    public void rotate(int[][] matrix) {
            int l=matrix.length;
            for(int i=0;i<(l+1)/2;i++){//this two lines can make if the size of the array is odd, loop contains
                for(int j=0;j<l/2;j++){//(size-1)/4 steps, if the size is even, loop contains size/4 steps.
                    int p=matrix[i][j];
                    matrix[i][j]=matrix[l-1-j][i];
                    matrix[l-1-j][i]=matrix[l-1-i][l-1-j];
                    matrix[l-1-i][l-1-j]=matrix[j][l-1-i];
                    matrix[j][l-1-i]=p;
                }
            }
        }
    

  • 0

    @chuck_long Your current post is much better, but I think the explanation part can be further improved. What do you say?


  • 1

    @LHearen Thank you for your advice! I have rewritten the explanation.


Log in to reply
 

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