-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathsol.java
67 lines (53 loc) · 1.62 KB
/
sol.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public class sol {
public static void main(String[] args) {
// call the fn here
}
public class Solution {
public ListNode[] splitListToParts(ListNode head, int k) {
int length = 0;
ListNode current = head;
List<ListNode> parts = new ArrayList<>();
while (current != null) {
length++;
current = current.next;
}
int base_size = length / k, extra = length % k;
current = head;
for (int i = 0; i < k; i++) {
int part_size = base_size + (extra > 0 ? 1 : 0);
ListNode part_head = null, part_tail = null;
for (int j = 0; j < part_size; j++) {
if (part_head == null) {
part_head = part_tail = current;
} else {
part_tail.next = current;
part_tail = part_tail.next;
}
if (current != null) {
current = current.next;
}
}
if (part_tail != null) {
part_tail.next = null;
}
parts.add(part_head);
extra = Math.max(extra - 1, 0);
}
return parts.toArray(new ListNode[0]);
}
}
}