[leetcode]Rotate Image @ Python

原题地址:https://oj.leetcode.com/problems/rotate-image/

题意:

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?

解题思路1:首先沿着副对角线翻转一次,然后沿着水平中线翻转一次,就可以得到所要求的矩阵了。时间复杂度O(n^2),空间复杂度O(1)

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        #思路1,时间复杂度O(n^2),空间复杂度O(1)
        n = len(matrix)
        for i in range(n):
            for j in range(n-i): #沿着副对角线反转
                matrix[i][j], matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i], matrix[i][j]
        for i in range(n/2):     #沿着水平中线反转
            for j in range(n):
                matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j]
        return matrix

 

解题思路2:先将矩阵转置,然后将矩阵的每一行翻转,就可以得到所要求的矩阵了。

reference: http://www.cnblogs.com/zuoyuan/p/3772978.html

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        n = len(matrix)
        for i in range(n): 
            for j in range(i+1, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]  #先将矩阵转置
        for i in range(n):
            matrix[i].reverse()  #然后将矩阵的每一行翻转
        return matrix

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。