折腾了好久。。写得好繁琐。。相当于试出来的
运行时间:27ms
占用内存:5852k
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
if m==1:
return matrix[0]
if n==1:
return [b[0] for b in matrix]
i = m//2
j = n//2
result = []
cnt = 1
while (i and j):
if(i):
#第cnt个循环的行正向
result += matrix[cnt-1][cnt-1:(n-1)-cnt +1]
if j:
#第cnt个循环的列正向
result += [b[(n-1)-(cnt-1)] for b in matrix[cnt-1:(m-1)-cnt +1]]
#第cnt个循环的行负向
result += matrix[(m-1)-(cnt-1)][(n-1)-(cnt-1):cnt-1:-1]
if j:
#第cnt个循环的列负向
result += [b[cnt-1] for b in matrix[(m-1)-(cnt-1):cnt-1:-1]]
i -= 1
j -= 1
cnt += 1
#列为奇,且列小于等于行,再加一列
if n%2 and (not j):
result += [b[(n-1)-(cnt-1)] for b in matrix[cnt-1:(m-1)-cnt +1+1]]
return result
#行为奇,且行小于列
if m%2 and (not i):
result += matrix[cnt-1][cnt-1:(n-1)-cnt +1+1]
return result
return result
————————————————————————————————————————————
学会利用pop(),不管是一维,二维,还是在循环里,都有效
第一种,每次取第一列,然后旋转矩阵
运行时间:22ms
占用内存:5732k
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
def turn(mat):
if (not mat) or (not mat[0]):
return None
#m = len(mat)
n = len(mat[0])
result = []
for i in range(n):
result.append([a[n-i-1] for a in mat[:]])
return result
res = []
while (matrix and matrix[0]):
res += matrix.pop(0)
matrix = turn(matrix)
return res
____________________________________________________
另一种更简洁的pop方法,不用每次旋转矩阵,只需要列也pop掉即可
运行时间:31ms
占用内存:5624k
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
res = []
while(matrix):
res += matrix.pop(0)
if(matrix and matrix[0]):
for row in matrix:
res.append(row.pop())
if matrix:
res += matrix.pop()[::-1]
if matrix and matrix[0]:
for row in matrix[::-1]:
res.append(row.pop(0))
return res