725. Split Linked List in Parts

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

 

k>=length, 每个部分有且仅有一个,剩下k-length个部分都是空

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

k<length,每个部分至少有length/k个,那么剩下的length%k个就要给每个部分匀一个

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]]

最终有:

前length%k个部分,size为(length/k)+1

剩下的部分size就是length/k

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode[] splitListToParts(ListNode root, int k) {
11         ListNode[] result = new ListNode[k];
12         int length = 0;
13         for (ListNode cursor = root; cursor != null; cursor = cursor.next) {
14             length++;
15         }
16         int perPartNum = length / k;
17         int remainNum = length % k;
18         ListNode head = root;
19         ListNode perPartTail = null;
20         for(int i = 0; i < k; i++, remainNum--){
21             result[i] = head;
22             for(int j = 0; j<perPartNum+(remainNum> 0 ? 1 : 0); j++){
23                 perPartTail = head;
24                 head = head.next;
25             }
26             if(perPartTail != null){
27                 perPartTail.next = null;
28             }
29         }
30         return result;
31     }
32 }
remainNum就是需要匀出去的部分,最开始的几个在分配的时候就会多一个
posted @ 2018-12-21 12:45  三人木君  阅读(196)  评论(0编辑  收藏  举报