classSolution:defspiralOrder(self, matrix: List[List[int]])-> List[int]:ifnot matrix:return[]
m=len(matrix)#行
n=len(matrix[0])#列
layer_num=(min(m,n)+1)//2#有多少层
res_list=[]#保持结果for lr inrange(layer_num):
start=lr #左上角
last_col=n-lr-1#该层最后一列索引
last_row=m-lr-1for i inrange(start, last_col+1):#遍历左右
res_list.append(matrix[start][i])#加入此行?for j inrange(start+1,last_row+1):#遍历上下,+1去重
res_list.append(matrix[j][last_col])#加入此列if last_col!=start and last_row!=start:for ii inrange(last_col-1,start-1,-1):# 右→左
res_list.append(matrix[last_row][ii])#右到左的顺序放入for ij inrange(last_row-1,start,-1):#下→上
res_list.append(matrix[ij][start])#下到上的顺序放入return res_list
螺旋矩阵
classSolution:defgenerateMatrix(self, n:int)-> List[List[int]]:
x=1
y=1
direct=[(0,1),(1,0),(0,-1),(-1,0)]#变化量
turn=0
ans=[]
ans.append([-1]*(n+2))for i inrange(0,n):
ans.append([-1]+[0]*n+[-1])#-1为边界,遇到边界就转向
ans.append([-1]*(n+2))for i inrange(1,n*n+1):if ans[x][y]==0:
ans[x][y]=i
if ans[x+direct[turn][0]][y+direct[turn][1]]!=0:
turn=(turn+1)%4
x+=direct[turn][0]
y+=direct[turn][1]
re_ans=[a[1:n+1]for a in ans[1:n+1]]return re_ans
旋转链表
classSolution:defrotateRight(self, head: ListNode, k:int)-> ListNode:ifnot head ornot head.nextornot k:return head
tail, count= head,1#头尾,链表长度while tail.next:
tail = tail.next#找到旧链表尾部
count +=1
k = k % count #旋转多少次if k ==0:return head
newTail = newHead = head
for i inrange(count - k):#目前的头部
newHead = newHead.nextfor j inrange(count - k -1):
newTail = newTail.next
newTail.next=None#打破闭环
tail.next= head
return newHead