Posted on 2023-09-06 21:51
Uriel 阅读(35)
评论(0) 编辑 收藏 引用 所属分类:
数据结构 、
闲来无事重切Leet Code
把一个单链表均分分成k份,预先计算每份的节点数量以及最后剩下多少节点
1 #725
2 #Runtime: 15 ms (Beats 93.44%)
3 #Memory: 13.6 MB (Beats 73.77%)
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def splitListToParts(self, head, k):
12 """
13 :type head: ListNode
14 :type k: int
15 :rtype: List[ListNode]
16 """
17 n = 0
18 p = head
19 pre = None
20 while p:
21 n += 1
22 p = p.next
23 l, t = n//k, n%k
24 p = head
25 ans = []
26 for i in range(k):
27 ans.append(p)
28 for _ in range(l):
29 if p:
30 pre = p
31 p = p.next
32 if t and p:
33 pre = p
34 p = p.next
35 t -= 1
36 if pre:
37 pre.next = None
38 return ans