zoukankan      html  css  js  c++  java
  • 48. Rotate Image

    https://leetcode.com/problems/rotate-image/#/description

    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?

    Sol 1:

    class Solution(object):
        def rotate(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            # Time O(n^2) Space(1)
            n = len(matrix)
            # flip the matrix alongside the counter-diagonal
            for i in range(n):
                for j in range(n-i):
                    self.swap(matrix, i, j, n - 1 - j, n - 1 - i)
            # flip alongside the horizontal center line
            for i in range(n/2):
                for j in range(n):
                    self.swap(matrix, i, j, n - 1 - i, j)
                    
        def swap(self, matrix, i, j, p, q):
            tmp = matrix[i][j]
            matrix[i][j] = matrix[p][q]
            matrix[p][q] = tmp

    Sol 2 :

    class Solution(object):
        def rotate(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            # Time O(n^2) Space(1)
            n = len(matrix)
            # flip alongside the horizontal center line
            for i in range(n/2):
                for j in range(n):
                    self.swap(matrix, i, j, n - 1 - i, j)
            # flip the matrix alongside the diagonal
            for i in range(n):
                for j in range(i+1, n):
                    self.swap(matrix, i, j, j,i)
    
                    
        def swap(self, matrix, i, j, p, q):
            tmp = matrix[i][j]
            matrix[i][j] = matrix[p][q]
            matrix[p][q] = tmp
  • 相关阅读:
    kindeditor的使用
    阅读笔记(三)
    阅读笔记(二)
    架构漫谈
    阅读笔记(一)
    hdfs
    暑假周总结八
    暑假周总结七
    暑假周总结六
    暑假周总结五
  • 原文地址:https://www.cnblogs.com/prmlab/p/7231099.html
Copyright © 2011-2022 走看看