zoukankan      html  css  js  c++  java
  • leetcode 【 Rotate Image 】python 实现

    题目

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

    Rotate the image by 90 degrees (clockwise).

    Follow up:
    Could you do this in-place?

    代码:oj测试通过 Runtime: 53 ms

     1 class Solution:
     2     # @param matrix, a list of lists of integers
     3     # @return a list of lists of integers
     4     def rotate(self, matrix):
     5         if matrix is None:
     6             return None
     7         if len(matrix[0]) < 2 :
     8             return matrix
     9         
    10         N = len(matrix[0])
    11         
    12         for i in range(0, N/2, 1):
    13             for j in range(i, N-i-1, 1):
    14                 ori_row = i
    15                 ori_col = j
    16                 row = ori_row
    17                 col = ori_col
    18                 for times in range(3):
    19                     new_row = col
    20                     new_col = N-row-1
    21                     matrix[ori_row][ori_col],matrix[new_row][new_col] = matrix[new_row][new_col],matrix[ori_row][ori_col]
    22                     row = new_row
    23                     col = new_col
    24         return matrix

    思路:

    题意是将一个矩阵顺时针旋转90°

    小白的解决方法是由外层向里层逐层旋转;每层能够组成正方形对角线的四个元素依次窜一个位置(a b c d 变成 d a b c)。

    四个元素转换位置的时候用到一个数组操作的技巧,每次都要第一个位置的元素当成tmp,交换第一个位置的元素与指针所指元素的位置。

    原始:a b c d

    第一次交换:b a c d

    第二次交换:c a b d

    第三次交换:d a b c

    这样的好处是代码简洁一些 思路比较连贯

    Tips:

    每层循环的边界条件一定要考虑清楚,小白一开始最外层循环的上届一直写成了N,导致一直不通过,实在是太低级的错误。以后还要加强代码的熟练度,避免出现这样的低级判断错误。

  • 相关阅读:
    hdu 1496 equations(哈希)
    为什么要微服务化
    什么是分布式系统中的幂等性
    不积跬步无以至千里
    服务治理与微服务
    使用阿里开源工具 TProfiler 在海量业务代码中精确定位性能代码 (jvm性能调优)
    Spring MVC重定向和转发
    两个实体复制
    IntelliJ IDEA类头注释和方法注释
    Linux下单机安装部署kafka及代码实现
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4232578.html
Copyright © 2011-2022 走看看