Leetcode 725. Split Linked List in Parts

Description: Given a (singly) linked list with head node root, write a function to 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 1. This may lead to some parts being null. The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode's representing the linked list parts that are formed.

Link: https://leetcode.com/problems/split-linked-list-in-parts/

Examples:

Example 1:
Input: root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]

Example 2:
Input:  root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]

思路: 将单链表分成连续的k段,每段的长度差不得超过1,长的放在待返回 list 的前面,返回list of ListNode. 所以问题在于想清楚怎么将长度为length的list分成k段,且每段长度差不超1. 当length <= k时, 所有节点next setting as None 且 补足k-length 个None; 当length > k时,length // k = num, length % k = reminder, reminder < k; 所以正常来说,如果可以整除,那么每段有num 个节点,但是如果有余数reminder, 就要将余数平分,因为difference must be 1, 所以k段中的前reminder个每个里面多加一个节点。

class Solution(object):
    def splitListToParts(self, root, k):
        """
        :type root: ListNode
        :type k: int
        :rtype: List[ListNode]
        """
        
        rl = list()
        if not root:
            i = 0
            while i < k:
                rl.append(None)
                i += 1
            return rl
        p = root
        nodes = list()
        while p:
            nodes.append(p)
            p = p.next
        length = len(nodes)
        if length <= k:
            for n in nodes:
                n.next = None
            return nodes + [None]*int(k-length)
        else:
            num = length // k
            rest = length % k
            i = 0
            while i < length:
                rl.append(nodes[i])
                if rest > 0:
                    nodes[i+num].next = None
                    i = i+num+1
                    rest -= 1
                else:
                    nodes[i+num-1].next = None
                    i = i+num
            return rl

日期: 2020-12-08  最近实验结果不好,做题的心情都没有了...

原文地址:https://www.cnblogs.com/wangyuxia/p/14100820.html