Well commented java in-place-rotating solution.


  • 1
    Y
    public class Solution {
    public void rotate(int[][] matrix) {
        /*
        Rotate in place, need only one int rather than a new array.
        O(1) space O(n^2) time
        */
        int n = matrix.length;
        int iterate = n/2;  //if the matrix is sorted in place, we only need to iterate through half of the points
        for (int i = 0; i <iterate; i ++){
            int index = n - i - 1; 
            for (int j = i; j < index; j ++){ //if i means row, then we only need to iterate through i to index in column. Since all other points before i and after index have been already rotated before.
                int temval = matrix[i][j]; //although we want to rotate in place, we still need at least one integer to store the one that is reassigned before being used.
                matrix[i][j] = matrix[n-1-j][i];  //the rotate happened in circle between 4 points. [i][j] = [j][n-1-i]
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
                matrix[j][n-1-i] = temval;
            }
        }
        
    }
    

    }


Log in to reply
 

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