C# Solution


  • 0
    J

    Straightforward: The idea is to count the number of nodes and split it evenly. If there are extra nodes assign it to the first occurring nodes.

     public ListNode[] SplitListToParts(ListNode root, int k) {
                var res = new ListNode[k];
                if (root == null) return res;
                var temp_res = new ListNode[k];
                int count = 0;
                var ptr = root;
                var r = root;
    
                while (r != null)
                {
                    count++;
                    r = r.next;
                }
    
                int num_Extra = count % k;
                int filler = count / k;
                int counter = 0;
    
                while (ptr != null)
                {
                    int i = 0;
                    int j = filler;
    
                    if (counter < num_Extra) j++;
    
                    while (i < j && ptr != null)
                    {
                        if (i == 0)
                        {
                            res[counter] = new ListNode(ptr.val);
                            temp_res[counter] = res[counter];
                        }
                        else
                        {
                            temp_res[counter].next = new ListNode(ptr.val);
                            temp_res[counter] = temp_res[counter].next;
                        }
    
                        ptr = ptr.next;
                        i++;
                    }
    
                    counter++;
                }
    
                return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.