Leetcode 48. Rotate Image
- 题目
- 解法:
- follow up1: 逆时针旋转90度
- follow up 2:旋转180度
题目
解法:
先transpose,然后把每行reverse
class Solution:def rotate(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""n = len(matrix)# transposefor i in range(n):for j in range(i,n):matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]# reverse by rowfor i in range(n):matrix[i] = matrix[i][::-1]
follow up1: 逆时针旋转90度
先reverse行,再transpose
class Solution:def rotate(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""n = len(matrix)# reverse by rowfor i in range(n):matrix[i] = matrix[i][::-1]# transposefor i in range(n):for j in range(i,n):matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j]
follow up 2:旋转180度
先reverse行,然后reverse列
class Solution:def rotate(self, matrix: List[List[int]]) -> None:"""Do not return anything, modify matrix in-place instead."""n = len(matrix)# reverse rowfor i in range(n):matrix[i] = matrix[i][::-1]# reverse columnfor j in range(n):up = 0down = n-1while up<down:matrix[up][j],matrix[down][j] = matrix[down][j],matrix[up][j]up+=1down-=1