In place, simple Math trick with property of rotating


  • 0
    K
    public class Solution {
        // (n, m) --> rotate to be (m, matrix.length -n)
        // only rotate i --> matrix.length-1 (not inclusive) j = i-->matrix.length -1(not inclusive)
        // if n %2 == 1, the number in the middle no need to rotate
        public void rotate(int[][] matrix) {
            if (matrix == null || matrix.length == 0) {
                return ;
            }
            int n = matrix.length;
            for (int i = 0; i < n-1; i++) {
                for (int j = i; j<n -i -1; j++) {// n -i -1 <-- i + n - i* 2 -1
                    int temp = matrix[i][j];
                    matrix[i][j] = matrix[n -1- j][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] = temp;
                }
            }
            
        }
    }
    

Log in to reply
 

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