知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 48. Rotate Image (Medium/Python)

코방코 2022. 9. 5. 07:49
728x90
 

Rotate Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Above is the link to the problem.

 

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

Do not allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

 

I solved this problem by writing the code below.

 

 

Get the first element of each column in order, and when we get all the columns, reverse it.

Then it corresponds to the original matrix.

 

But this solution solved the problem by allocating a new matrix.

Looking at the solution written by someone else, They immediately turned the matrix 90 degrees using numpy.

#Rotate the matrix 90 degrees counterclockwise
numpy.rot90(numpy.array(matrix))

#Rotate the matrix 90 degrees clockwise
numpy.rot90(numpy.array(matrix),-1)

 

This code gets the top 45.63% of time efficiency and the top 25.68% of space efficiency.

 

728x90
반응형