Solution by cody8


  • 0
    C

    Approach #1 In place rotation

    Intuition

    We just need to rotate the number 4 times for each circle starting from outside.

    Algorithm

    From the outside circle, we rotate the first one on 4 sides, then rotate the second one on 4 sides, ... until all numbers are rotated.
    Then, we move to next inner circle and repeat the above procedure.

    Java

    class Solution {
        public void rotate(int[][] matrix) {
            for (int i = 0; i < matrix.length / 2; i++) {
                int len = matrix.length - 2 * i - 1;
                                                         
                for (int j = 0; j < len; j++) {
                    int temp = matrix[i][i + j + 1];
                    matrix[i][i + j + 1] = matrix[i + len - 1 - j][i];
                    matrix[i + len - 1 - j][i] = matrix[i + len][i + len - 1 - j];
                    matrix[i + len][i + len - 1 - j] = matrix[i + 1 + j][i + len];
                    matrix[i + 1 + j][i + len] = temp;
                }
            }
        }
    }
    

    Complexity Analysis

    • Time complexity : O(n^2).

    • Space complexity : O(1)


Log in to reply
 

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