leetcode----48. Rotate Image

链接:

https://leetcode.com/problems/rotate-image/

大意:

对一个二维数组,进行顺时针90度旋转。要求:原地置换,即空间复杂度为O(1).例子:

leetcode----48. Rotate Image

思路:

数学问题,找规律...从矩阵的最外围依次往内交换元素,详细请看代码及注释

代码:

class Solution {
    public void rotate(int[][] matrix) {
        if (matrix.length <= 1)
            return ;
        helper(matrix, 0, matrix.length - 1, matrix.length - 1);
    }
    /*
    n * n的矩阵
    每一次helper把矩阵的最外围数字按规律交换
    初始 rowStart = 0 rowEnd = matrix.length - 1 
    假设matrix矩阵为 5 * 5
    规律: 
    matrix[0][0] -> matrix[0][4]
    matrix[0][4] -> matrix[4][4]
    matrix[4][4] -> matrix[4][0]
    matrix[4][0] -> matrix[0][0]
    其中 4 = matrix.length - 1   并且观察每个 -> 左右两个下标的关系:
    记左边下标为 index0 右边下标为 index1
    可以看到:index0[1] = index1[0]   index0[0] + index1[1] = 4(matrix.length - 1)
    另:因为是n*n的矩阵,所以传入行的范围就是列的范围
    */
    public void helper(int[][] matrix, int rowStart, int rowEnd, int gap) {
        if (rowStart >= rowEnd)
            return ;
        int rS = rowStart, rE = rowEnd;
        while (rS < rE) {
            int rowCur = rowStart, colCur = rS;
            int num1 = matrix[rowCur][colCur], num2 = matrix[colCur][gap - rowCur], 
            num3 = matrix[gap - rowCur][gap - colCur], num4 = matrix[gap - colCur][rowCur];
            // 按规律交换四个数
            matrix[colCur][gap - rowCur] = num1;matrix[gap - rowCur][gap - colCur] = num2;
            matrix[gap - colCur][rowCur] = num3;matrix[rowCur][colCur] = num4;
            rS++;
        }
        helper(matrix, rowStart + 1, rowEnd - 1,gap);
    }
}

结果:

leetcode----48. Rotate Image

结论:

数学题找规律,找到规律还得用代码实现...