LeetCode force buckle 48. Rotate image

Title Description (medium difficulty)

A matrix rotated 90 degrees clockwise, and does not use extra space. Probably belong to find the law of the question, there is no general ideas, observe it.

A Solution

Can first transpose, then each column symmetrical about switching exchange.

public void rotate(int[][] matrix) {
    //以对角线为轴交换
    for (int i = 0; i <  matrix.length; i  ) {
        for (int j = 0; j <=i; j  ) {
            if (i == j) {
                continue;
            }
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    } 
    //交换列
    for (int i = 0, j = matrix.length - 1; i < matrix.length / 2; i  , j--) {
        for (int k = 0; k < matrix.length; k  ) {
            int temp = matrix[k][i];
            matrix[k][i] = matrix[k][j];
            matrix[k][j] = temp;
        }
    }

} 

Time complexity: O (n²).

Complexity Space: O (1).

You can first axis transverse to the axis of symmetry of the line exchange, then switching to a diagonal.

Solution two

I put this link ideas posted over, inside comments also take the opportunity to have a chart posted over it and write well.

Circle around the loop interchange, it is wonderful!

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

Time complexity: O (n²).

Complexity Space: O (1).

total

This question is the subject of features were observed on it.

For more detailed explanations of popular leetcode.wang .

Published 61 original articles · won praise 7 · views 20000 +

Guess you like

Origin blog.csdn.net/wind_liang/article/details/104074103