classSolution:defspiralOrder(self, matrix: List[List[int]])-> List[int]:
m =len(matrix)
n =len(matrix[0])
layer_num =(min(m,n)+1)//2
res =[]for layer inrange(layer_num):
start = layer
last_col = n-1-layer #最后一列的下标
last_row = m-1-layer #最后一行的下标for j inrange(start, last_col+1):#from left to right
res.append(matrix[start][j])for j inrange(start+1, last_row+1):#from top to bottom
res.append(matrix[j][last_col])if start != last_row and start != last_col:for j inrange(last_col-1,start-1,-1):#from right to left
res.append(matrix[last_row][j])for j inrange(last_row-1, start,-1):# from bottom to top
res.append(matrix[j][start])return res
59 螺旋矩阵Ⅱ
classSolution:defgenerateMatrix(self, n:int)-> List[List[int]]:
matrix =[[0]*n for _ inrange(n)]# print(matrix)
layer_num =(n+1)//2
count =0for layer inrange(layer_num):
start = layer
last_idx = n-1-layer
# last_row = n-1-layerfor i inrange(start,last_idx+1):
count +=1
matrix[start][i]= count
for i inrange(start+1, last_idx+1):
count +=1
matrix[i][last_idx]= count
if start != last_idx:for i inrange(last_idx-1, start-1,-1):
count +=1
matrix[last_idx][i]= count
for i inrange(last_idx-1, start,-1):
count +=1
matrix[i][start]= count
return matrix
61 旋转链表
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defrotateRight(self, head: ListNode, k:int)-> ListNode:ifnot head:return head
p = head
n =1while p.next:
n +=1
p = p.next
k = k%n # 防止循环太多无用次数for i inrange(k):
pre =None
cur = head
while cur.next:
pre = cur
cur=cur.nextifnot pre:return head
cur.next= head
pre.next=None
head = cur
return head