Ac solution code


  • 3
    Original:
    1  2  3             
    4  5  6
    7  8  9
    

    The matrix can be rotated in-place by clockwise 90 degrees with the following two steps:

    1. Transpose by anticlockwise 90 degrees: swap(matrix[i][j], matrix[j][i]).
    1  4  7
    2  5  8
    3  6  9
    
    2. Flip symmetrically: swap(matrix[i][j], matrix[i][matrix.length-1-j].
    7  4  1
    8  5  2
    9  6  3
    

    JAVA Code: Time complexity = O(n^2)

    public void rotate(int[][] matrix) {
    	int n = matrix.length;
    	// Transpose by anticlockwise 90 degrees 
    	for (int i = 0; i < n; i++) {
    		for (int j = i; j < n; j++) {// j: i .. n - 1
    			int tmp = matrix[i][j]; 
    			matrix[i][j] = matrix[j][i];
    			matrix[j][i] = tmp;						
    		}
    	}	
    	// Flip symmetrically
    	for (int i = 0; i < n; i++) {
    		for (int j = 0; j < n / 2; j++) {// j: 0 .. n/2 - 1
    			int tmp = matrix[i][j];
    			matrix[i][j] = matrix[i][n - 1 - j];
    			matrix[i][n - 1 - j] = tmp;						
    		}
    	}
    }

Log in to reply
 

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