Leetcode 725. Split Linked List in Parts
If there are N nodes in the linked list root, then there are N / k items in each part, plus the first N%k parts have an extra item.
有N个节点,前N%k个部分有 (N/k + N%k )个数字,其余有N/k。
Approach #1: Create New Lists [Accepted]
class Solution {
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode cur = root;
int N = 0;
while (cur != null) {
cur = cur.next;
N++;
}
int width = N / k, rem = N % k;
ListNode[] ans = new ListNode[k];
cur = root;
for (int i = 0; i < k; ++i) {
ListNode head = new ListNode(0), write = head;
for (int j = 0; j < width + (i < rem ? 1 : 0); ++j) {
write = write.next = new ListNode(cur.val);
if (cur != null) cur = cur.next;
}
ans[i] = head.next;
}
return ans;
}
}
Approach #2: Split Input List [Accepted]
class Solution {
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode cur = root;
int N = 0;
while (cur != null) {
cur = cur.next;
N++;
}
int width = N / k, rem = N % k;
ListNode[] ans = new ListNode[k];
cur = root;
for (int i = 0; i < k; ++i) {
ListNode head = cur;
for (int j = 0; j < width + (i < rem ? 1 : 0) - 1; ++j) {
if (cur != null) cur = cur.next;
}
if (cur != null) {
ListNode prev = cur;
cur = cur.next;
prev.next = null;
}
ans[i] = head;
}
return ans;
}
}