使用O(1)额外空间将方阵旋转90度。我用Python来解决它。我想知道我是否可以进一步改进我的代码。
def rotate_by_90(m):
# unpacking arguments with zip(*) in reverse with [ : :-1]
tuples = zip(*m[::-1])
# flattening tuples to list with [list(i)]
return [list(i) for i in tuples]
def makeMatrix(array, size):
# validating size of matrix for given array
if (size**2!=len(array)):
return -1
# make sub array of length size using array slicing
else:
matrix = [array[i:i+size] for i in range(0, len(array), size)]
return rotate_by_90(matrix)
arr = [1,2,3,4]
dimension = 2
result = makeMatrix(arr, dimension)
# Original Matrix: [[1, 2], [3, 4]]
# Result: [[3, 1], [4, 2]]
答案 0 :(得分:2)
不需要外部库或zip。使用它进行采访:
def rotate_by_90(m):
a.reverse()
for i in range(len(a)):
for j in range(i):
a[i][j], a[j][i] = a[j][i], a[i][j]
return a
答案 1 :(得分:0)
如果您正在寻找速度,那么您使用的是错误类型的数组。您需要切换到numpy数组而不是列表。在Numpy中,当然有这样的操作函数:rot90