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
  • 相关阅读:
    分糖果
    数字游戏
    错误票据
    包子凑数
    带分数
    翻硬币
    核桃的数量
    快速幂
    公倍数与素数筛选
    mysql 查询当天当周当月的数据
  • 原文地址:https://www.cnblogs.com/prmlab/p/7231099.html
Copyright © 2011-2022 走看看