1 | class Solution(object): |
- 时间复杂度:O(N),N是指元素数量
- 空间复杂度:O(N),N是ans长度
1 | class Solution(object): |
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return matrix
m, n = len(matrix), len(matrix[0])
if m == 0 or n == 0:
return matrix
res = []
start = 0
while m > start * 2 and n > start *2:
endX = m - start - 1
endY = n- start -1
for i in range(start, endY+1):
res.append(matrix[start][i])
if start < endX:
for i in range(start+1, endX+1):
res.append(matrix[i][endY])
if start < endY and start < endX:
for i in range(endY-1, start-1, -1):
res.append(matrix[endX][i])
if start + 1 < endX and start < endY:
for i in range(endX-1, start, -1):
res.append(matrix[i][start])
start += 1
return res