Well documented O(n^2) java solution using O(1) space


  • 0
    J

    Unlike rotation solutions, it touches each element only once.

     class Solution {
        public void rotate(int[][] matrix) {
            int start = 0;
            int end = matrix.length - 1;
            
            int[] corners = new int[4];
            
            // peel like an onion, outer layer to inner
            // swap elements starting from the corners and moving clockwise
            while(start < end) {
                for(int offset = 0; offset < (end-start); offset++) {
                    corners[0] = matrix[start][start + offset]; // TL
                    corners[1] = matrix[start + offset][end];   // TR
                    corners[2] = matrix[end][end - offset];     // BR
                    corners[3] = matrix[end - offset][start];   // BL
    
                    matrix[start + offset][end]   = corners[0]; // TL to TR
                    matrix[end][end - offset]     = corners[1]; // TR to BR
                    matrix[end - offset][start]   = corners[2]; // BR to BL
                    matrix[start][start + offset] = corners[3]; // BL to TL
                }
                start++;
                end--;
            }
        }
    }
    

Log in to reply
 

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