给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
不占用额外内存空间能否做到?
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
Python 解答:
1.循环赋值
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
def helper(matrix, left, right):
if left < right:
temp = matrix[left][left:right+1]
for i in range(left, right+1):
matrix[left][right-i+left] = matrix[i][left]
for i in range(left, right+1):
matrix[i][left] = matrix[right][i]
for i in range(left, right+1):
matrix[right][i] = matrix[right-i+left][right]
for i in range(left, right+1):
matrix[i][right] = temp[i-left]
helper(matrix, left+1, right-1)
helper(matrix, 0, len(matrix)-1)
2.两次翻转
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
length = len(matrix)
for i in range(length//2):
for j in range(length):
matrix[i][j], matrix[length-i-1][j] = matrix[length-i-1][j], matrix[i][j]
for i in range(0, length):
for j in range(i+1, length):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
留言