• 【LeetCode with Python】 Rotate Image


    博客域名:http://www.xnerv.wang
    原标题页:https://oj.leetcode.com/problems/rotate-image/
    题目类型:下标计算
    难度评价:★★★
    本文地址:http://blog.csdn.net/nerv3x3/article/details/37968757

    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?


    顺时针90度转动一个二维矩阵,要求in-place的算法,也就不是不能另外开一个新的矩阵然后把原矩阵上的元素一个个相应复制过来,而要在原矩阵上进行操作。


    眼下能想到的有两种方法。
    第一种比較直观,首先将原矩阵依照水平轴上下翻转,然后依照左上到右下的对角线再反转,则等价于90度顺时针转动。这种方法的缺点是要反转两次,长处是直观,不easy出错。
    另外一种方法每一个元素仅仅须要调整一次,可是转化公式会比較复杂。对于矩阵matrix[n][n]中的某一点matrix[x][y](0<=x, y<n),90度顺时针转动后到了matrix[y][n-x-1],而matrix[y][n-x-1]到了matrix[n-x-1][n-y-1]。matrix[n-x-1][n-y-1]到了matrix[n-y-1][x],matrix[n-y-1][x]又到了matrix[x][y],可见这四个点正好实现了一次旋转互换。
    本文採用另外一种方法。空间复杂度O(1)。时间复杂度O(n*n)。

    class Solution:
        # @param matrix, a list of lists of integers
        # @return nothing (void), do not return anything, modify matrix in-place instead.
        def rotate(self, matrix):
            n = len(matrix)
            if 1 == n:
                return
            round = int(n / 2)
            for x in range(0, round):
                for y in range(x, n - x - 1):
                    matrix[n - y - 1][x], matrix[n - x - 1][n - y - 1], matrix[y][n - x - 1], matrix[x][y] = matrix[n - x - 1][n - y - 1], matrix[y][n - x - 1], matrix[x][y], matrix[n - y - 1][x]

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    gnuplot
    charles证书安装
    jenkins 配置ssh
    jenkins 配置slave
    centos 安装jenkins
    mac的一些命令
    docker 常用命令
    GO vim环境
    go vendor目录
    protobuf
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4657100.html
Copyright © 2020-2023  润新知