2ms rotate


  • 0
    T

    [0_1521714475972_(_VJA9PTJ]MJT~}5J@)SCW.png
    思路:将二维数组通过对角线划分为 4 个区域,旋转 90° 其实可以分为 4 个步骤(i1,j1 表示 1 区域的坐标,i2,j2 表示 2 区域……):

    1. 1区域数字转移到 2 区域 (i2,j2) == (n-j2-1, i2)
    2. 2区域数字转移到 3 区域 (i3,j3) == (n-j3-1, i3)
    3. 3区域数字转移到 4 区域 (i4,j4) == (n-j4-1, i4)
    4. 4区域数字转移到 1 区域 (i1,j1) == (n-j1-1, i1)
       public void trans(int[][] source) {
            int t = 0;
    
            /**
             * 只需遍历1区数组,通过坐标运算,即可完成4个区域的数字转换
             */
            for (int i = 0; i < source.length; i++) {
                for (int j = i; j < source[i].length - i - 1; j++) {
                    // 暂存 1 区域数值
                    t = source[i][j];
                    //4区域数字转移到 1 区域
                    source[i][j] = source[source[i].length - 1 - j][i];
                    //3区域数字转移到 4 区域
                    source[source[i].length - 1 - j][i] = source[source[i].length - 1 - i][source[i].length - 1 - j];
                    //2区域数字转移到 3 区域
                    source[source[i].length - 1 - i][source[i].length - 1 - j] = source[j][source[i].length - 1 - i];
                    //1区域数字转移到 2 区域
                    source[j][source[i].length - 1 - i] = t;
                }
            }
    
            return source;
        }
    

Log in to reply
 

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