A o(n^2) solution for java! just two for loop! with explanation!!!


  • 0
    D

    because if we want to rotate a matrix,form each side, we can always get 4 number, and then draw a square, so we just need to exchange the position of these number, like a 4*4 matrix, form outside to inside, there is 2 squares.

    class Solution {
    public void rotate(int[][] matrix) {
    int n = matrix.length;
    int k;
    if(n == 2){ k = 1;}else { k = n-2;}// in order to consider the length is 2;
    for(int i = 0; i <k ; i++){ // why i< n-2? because a n x n matrix has n-2 square at most!
    for(int j = i; j<n-(i+1); j++){// this loop we exchange 4 numbers' position!
    int t1 = matrix[j][n-1-i];//[1][2]
    matrix[j][n-1-i] = matrix[i][j];//x 4
    int t2 = matrix[n-1-i][n-1-j];//[][]
    matrix[n-1-i][n-1-j] = t1;
    t1 = matrix[n-1-j][i];
    matrix[n-1-j][i] = t2;
    matrix[i][j] = t1;
    }
    }
    }
    }


Log in to reply
 

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