An clean and easy java code with 1ms


  • 6
    C
    public void rotate(int[][] matrix) {
        if (matrix == null) {
    		return;
    	}
    	
    	int row = matrix.length;
    	int col = matrix.length;
        
    	//step 1:switch column
        int low =0,high = col-1;
        while(low < high){
        	int[] temp = matrix[low];
        	matrix[low] = matrix[high];
        	matrix[high] = temp;
        	low++;
        	high--;
        }
        
        //step 2:对称元素交换
        for(int i=0; i<row; i++){
        	for(int j=0; j<i; j++){
        		int temp = matrix[i][j];
        		matrix[i][j] = matrix[j][i];
        		matrix[j][i] = temp;
        	}
        }
    }

  • 0
    Z

    Fantastic.
    step1. upside down.
    step2. transpose.

    In your code I see elegance.


  • 0
    Y

    the first while loop, you should call them row not column


Log in to reply
 

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