No function of swap, No extra space at all(O(0) space), Fully in-place algorithm


  • 0
    D

    General idea is for the 4 element in the rotate sequence, using 3 in-place swap.

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

Log in to reply
 

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