[leetcode-python3] 48. Rotate Image
1547 ワード
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
2階建てのドアを交換してくれました
行列範囲が狭いので大丈夫です.
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()
調べてみると、ソリューションも二重for文を使っています
脈絡は同じだと信じています.
Reference
この問題について([leetcode-python3] 48. Rotate Image), 我々は、より多くの情報をここで見つけました
https://velog.io/@jsh5408/leetcode-python3-48.-Rotate-Image
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
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
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()
Reference
この問題について([leetcode-python3] 48. Rotate Image), 我々は、より多くの情報をここで見つけました https://velog.io/@jsh5408/leetcode-python3-48.-Rotate-Imageテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol