Loading...

09-06 leetcode-0725

链接 725. Split Linked List in Parts

题目

Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.

The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.

The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.

Return an array of the k parts.

题解

这题的关键点在于尽可能的均分,且相差不要超过1,那么求余数然后分摊就可以了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from typing import Optional


class ListNode:
def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
self.val = val
self.next = next


class Solution:
def splitListToParts(
self, head: Optional["ListNode"], k: int
) -> list[Optional["ListNode"]]:
dummy = ListNode(-1, head)
count = 0
while head:
count += 1
head = head.next
head = dummy.next
split_size, remain_size = divmod(count, k)
results = []
while head:
current_size = split_size
if remain_size > 0:
current_size += 1
remain_size -= 1
results.append(head)
for _ in range(current_size - 1):
head = head.next
if not head:
break
head.next, head = None, head.next
results.extend([None] * (k - len(results)))
return results

Comment