LC 725. Split Linked List in Parts

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.

Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]

Example 1:

Input: 
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].

 

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]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

 

Note:

  • The length of root will be in the range [0, 1000].
  • Each value of a node in the input will be an integer in the range [0, 999].
  • k will be an integer in the range [1, 50].

 attention:

a = rootlen / k

b = rootlen % k 

a is the basic elements that will appear in every k array.

b is the more elements that pre-b array need to append.

eg.

[1,2,3,4,5,6,7]

rootlen = 7, k  = 4

a = 1

b = 2

so 

loop 1, append a(1) elements from root.

[[1] [] [] []] , b > 0   => [[1,2],[],[],[]], b = b-1 (1)

loop2 append a(1) elements from root.

[[1,2],[3],[],[]], b>0 => [[1,2],[3,4],[],[]] b = b-1(0)

loop 3 ....

Runtime: 3 ms, faster than 98.84% of Java online submissions for Split Linked List in Parts.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
  public ListNode[] splitListToParts(ListNode root, int k) {
    int rootlen = 0;
    ListNode[] ln = new ListNode[k];
    ListNode tmp = root, tmpnext;
    while(tmp != null){
      tmp = tmp.next;
      rootlen++;

    }
    if(rootlen == 0) return ln;
    int a = rootlen % k;
    int b = rootlen / k;
    int cnt = 0;
    for(int i=0; i<k; i++) {
      if(root == null) continue;
      tmp = root;
      for(int j=0; j<b-1; j++){
        tmp = tmp.next;
      }
      if(a != 0 && b != 0) {
        tmp = tmp.next;
        a--;
      }
      tmpnext = tmp.next;
      tmp.next = null;
      ln[cnt++] = root;
      root = tmpnext;
    }
    return ln;
  }
}

 

posted @ 2019-01-12 20:14  yuxihong  阅读(102)  评论(0编辑  收藏  举报