[leetcode-python3] 48. Rotate Image

48. Rotate Image - python3

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

My Answer 1: Accepted (Runtime: 36 ms - 55.59% / Memory Usage: 14.3 MB - 38.63%)

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        matrix.reverse()
        for i in range(0, len(matrix)):
            for j in range(i, len(matrix)):
                temp = matrix[j][i]
                matrix[j][i] = matrix[i][j]
                matrix[i][j] = temp

이중 for 문으로 swap 해줬다
matrix 범위가 작은 편이라 괜찮은듯

Solution 1: (Runtime: 32 ms - 81.59% / Memory Usage: 14.1 MB - 66.01%)

class Solution:
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix[0])
        # transpose matrix
        for i in range(n):
            for j in range(i, n):
                matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

        # reverse each row
        for i in range(n):
            matrix[i].reverse()

찾아보니까 solution 들도 이중 for 문을 사용한다
맥락은 같다고 믿어요

좋은 웹페이지 즐겨찾기