leetcode-Rotate Image

题目

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

思路:

1、传统思路:将行和列互换,但是前期行换列的过程会影响到后期的行换列,所以要额外使用一个矩阵,暂存;花销 O(n)

可以先找个3阶的分析分析,观察它们的下标是怎么变化的?

AC代码如下:

public class Solution {
    public void rotate(int[][] matrix) {
         int m = matrix.length;
         int[][] replace = new int[m][m];
            //int n = matrix[0].length;
            if(m == 1) return;
            for(int i =0;i<m;i++){
                for(int j=0;j<m;j++){
                     replace[j][m-1-i]=matrix[i][j];
                }
            }
             for(int i =0;i<m;i++){
                for(int j=0;j<m;j++){
                    matrix[i][j] = replace[i][j];
                }
            }
    }
}

2、奇葩思路:由于是矩阵转变顺时针转90,那么可以先转最外圈 ->次内圈 ->次次内圈......这样,每次转换时,每圈都不相互影响。从而可以在原矩阵上进行,space = O(1)

public void rotate(int[][] matrix) {
    int n = matrix.length;
    for(int row=0; row<n/2; row++) {                        //这里是把每一位都右转到相应的位置
        for(int col=row; col<n-1-row; col++) {                //然后走内圈 , matrix[1][1]
            int tmp = matrix[row][col];                      
            matrix[row][col] = matrix[n-1-col][row];     //左 -> 上
            matrix[n-1-col][row] = matrix[n-1-row][n-1-col];    //  下 -> 左
            matrix[n-1-row][n-1-col] = matrix[col][n-1-row];    //  右 -> 下
            matrix[col][n-1-row] = tmp;     //把matrix[0][0] ->右     补齐!
        }
    }
}

优化space: 有什么优化 -> 怎么不借助外部空间来做 -> 操作的时候,前面的步骤影不影响后面的步骤?

优化time  : 怎么优化? -> 怎么一次遍历就能解决问题 -> 是设置 多个指针 ?    or    采用算法?(递归?)

态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
原文地址:https://www.cnblogs.com/neversayno/p/5384039.html