给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
代码(python)
classSolution:defspiralOrder(self, matrix: List[List[int]])-> List[int]:
u, d, l, f =0,len(matrix)-1,0,len(matrix[0])-1
res =[]while u <= d and l <= f:for i inrange(l, f +1):
res.append(matrix[u][i])
u +=1if u > d:breakfor i inrange(u, d +1):
res.append(matrix[i][f])
f -=1if l > f:breakfor i inrange(f, l -1,-1):
res.append(matrix[d][i])
d -=1if u > d:breakfor i inrange(d, u -1,-1):
res.append(matrix[i][l])
l +=1if l > f:breakreturn res
059-螺旋矩阵II
题目描述
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
代码(python)
classSolution:defgenerateMatrix(self, n:int)-> List[List[int]]:
u, d, l, f =0, n -1,0, n -1
res =[[0for _ inrange(n)]for _ inrange(n)]
temp =1# while temp <= n ** 2:while u <= d and l <= f:for i inrange(l, f +1):
res[u][i]= temp
temp +=1
u +=1if u > d:breakfor i inrange(u, d +1):
res[i][f]= temp
temp +=1
f -=1if l > f:breakfor i inrange(f, l -1,-1):
res[d][i]= temp
temp +=1
d -=1if u > d:breakfor i inrange(d, u -1,-1):
res[i][l]= temp
temp +=1
l +=1if l > f:breakreturn res
061-旋转链表
题目描述
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
代码(python)
# 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 ornot head.nextornot k:return head
tmp, count= head,0while tmp:
tmp = tmp.next
count +=1
k = k % count
if k ==0:return head
fast = slow = head
for i inrange(k):
fast = fast.nextwhile fast.next:
fast = fast.next
slow = slow.next
newHead = slow.next
slow.next=None
fast.next= head
return newHead
Leetcode 054-螺旋矩阵,059-螺旋矩阵II,061-旋转链表054-螺旋矩阵题目描述代码(python)059-螺旋矩阵II题目描述代码(python)061-旋转链表题目描述代码(python)054-螺旋矩阵题目描述给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。代码(python)class Solution: def spiralOrder(self, matrix: List[List[int]]) -&g