725. 分隔链表

题目链接 725. 分隔链表
思路 链表-模拟
题解链接 Python 模拟
关键点 1. 算链表长度 2. 计算余数 3. 落入余数部分应当多放1一个节点
时间复杂度 \(O(n)\)
空间复杂度 \(O(1)\)

代码实现:

class Solution:
    def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
        n = 0
        node = head
        while node:
            n += 1
            node = node.next

        quotient, remainder = divmod(n, k)
                
        parts = [None for _ in range(k)]
        i, curr = 0, head
        while i < k and curr:
            parts[i] = curr
            part_size = quotient + (1 if i < remainder else 0)
            for _ in range(part_size - 1):
                curr = curr.next
            curr.next, curr = None, curr.next
            i += 1
        return parts
posted @ 2024-09-11 00:15  WrRan  阅读(6)  评论(0编辑  收藏  举报