顺时针旋转矩阵(牛客)
面试中被问到空间复杂度O(1)的方式,没写好,下标着实折腾。
1、空间复杂度O(n*n)
#-*-coding:utf-8-*-
#python2.7
class Rotate:
def rotateMatrix(self, mat, n):
# write code here,
result=[]
for i in range(n):
temp=[]
for j in range(n):
temp.append(mat[n-j-1][i])
result.append(temp)
return result
2、空间复杂度O(1),从外向内每一层循环改变。
#-*-coding:utf-8-*-
#python2.7
class Rotate:
def rotateMatrix(self, mat, n):
# write code here,
for layer in range(n/2):
for i in range(layer,n-layer-1):
reserve=mat[layer][i]
mat[layer][i]=mat[n-i-1][layer]
mat[n-i-1][layer]=mat[n-layer-1][n-i-1]
mat[n-layer-1][n-i-1]=mat[i][n-layer-1]
mat[i][n-layer-1] = reserve
return mat
3、无需额外空间,需要使用异或特性原地交换。先转置再左右镜像交换。
不过由于python特性,无需swap函数,原地交换即可,参见Python为什么不需要swap(a, b)。
#-*-coding:utf-8-*-
#python2.7
class Rotate:
def rotateMatrix(self, mat, n):
# write code here,
for i in range(n):
for j in range(i):
mat[j][i],mat[i][j]=mat[i][j],mat[j][i]
for i in range(n):
for j in range(n/2):
mat[i][n-j-1],mat[i][j]=mat[i][j],mat[i][n-j-1]
return mat
网友评论