zoukankan      html  css  js  c++  java
  • "Coding Interview Guide" -- 将正方形矩阵顺时针转动90°

    题目

      给定一个N×N矩阵matrix,把这个矩阵调整成顺时针转动90°后的形式

      例如, 1    2    3    4

          5    6    7    8

                      9    10  11  12

         13  14  15  16

      顺时针转动90°后为:

            13   9   5  1

         14  10  6  2

         15  11  7  3

         16  12  8  4

    要求

      时间复杂度为O(1)

     1     public void rotate(int[][] matrix)
     2     {
     3         if(matrix == null || matrix.length != matrix[0].length || matrix.length == 0)
     4         {
     5             return;
     6         }
     7 
     8         int tR = 0;
     9         int tC = 0;
    10         int dR = matrix.length - 1;
    11         int dC = matrix[0].length - 1;
    12         while(tR < dR)
    13         {
    14             rotateEdge(matrix, tR++, tC++, dR--, dC--);  // 矩阵可以由左上角坐标及矩阵长和宽共同表示,或者由左上角坐标和右下角坐标联合表示
    15         }
    16     }
    17 
    18     public void rotateEdge(int[][] m, int tR, int tC, int dR, int dC)
    19     {
    20         int times = dC - tC;
    21         int temp = 0;
    22         for(int i = 0; i < times; i++)
    23         {
    24             temp = m[tR][tC + i];
    25             m[tR][tC + i] = m[dR - i][tC];
    26             m[dR - i][tC] = m[dR][dC - i];
    27             m[dR][dC - i] = m[tR + i][dC];
    28             m[tR + i][dC] = temp;
    29         }
    30     }

    来源:左程云老师《程序员代码面试指南》

  • 相关阅读:
    centos 配置php
    Linux下端口被占用解决
    LUOGU P1040 加分二叉树
    bzoj 1057: [ZJOI2007]棋盘制作
    1858: [Scoi2010]序列操作
    poj 2559 Largest Rectangle in a Histogram
    2018/7/19 模拟赛
    SPOJ 2916 GSS5
    BZOJ 4004: [JLOI2015]装备购买
    CF 549B Looksery Party
  • 原文地址:https://www.cnblogs.com/OoycyoO/p/10991640.html
Copyright © 2011-2022 走看看