LeetCode 刷题记录: 48. Rotate Image [Python]

原题

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

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.

思路

先转置再x轴颠倒。

代码

1
2
3
4
5
6
7
8
9
10
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)):
for j in range(i):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for i in range(len(matrix)):
matrix[i][:]=matrix[i][::-1]

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×