forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
38 lines (38 loc) · 1.05 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 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 n = 0;
ListNode cur = root;
while (cur != null) {
++n;
cur = cur.next;
}
// width 表示每一部分至少含有的结点个数
// remainder 表示前 remainder 部分,每一部分多出一个数
int width = n / k, remainder = n % k;
ListNode[] res = new ListNode[k];
cur = root;
for (int i = 0; i < k; ++i) {
ListNode head = cur;
for (int j = 0; j < width + ((i < remainder) ? 1 : 0) - 1; ++j) {
if (cur != null) {
cur = cur.next;
}
}
if (cur != null) {
ListNode t = cur.next;
cur.next = null;
cur = t;
}
res[i] = head;
}
return res;
}
}