|
| 1 | +/** |
| 2 | + * 725. Split Linked List in Parts |
| 3 | + * https://leetcode.com/problems/split-linked-list-in-parts/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the head of a singly linked list and an integer k, split the linked list into k |
| 7 | + * consecutive linked list parts. |
| 8 | + * |
| 9 | + * The length of each part should be as equal as possible: no two parts should have a size |
| 10 | + * differing by more than one. This may lead to some parts being null. |
| 11 | + * |
| 12 | + * The parts should be in the order of occurrence in the input list, and parts occurring |
| 13 | + * earlier should always have a size greater than or equal to parts occurring later. |
| 14 | + * |
| 15 | + * Return an array of the k parts. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * Definition for singly-linked list. |
| 20 | + * function ListNode(val, next) { |
| 21 | + * this.val = (val===undefined ? 0 : val) |
| 22 | + * this.next = (next===undefined ? null : next) |
| 23 | + * } |
| 24 | + */ |
| 25 | +/** |
| 26 | + * @param {ListNode} head |
| 27 | + * @param {number} k |
| 28 | + * @return {ListNode[]} |
| 29 | + */ |
| 30 | +var splitListToParts = function(head, k) { |
| 31 | + let count = 0; |
| 32 | + let current = head; |
| 33 | + |
| 34 | + while (current) { |
| 35 | + count++; |
| 36 | + current = current.next; |
| 37 | + } |
| 38 | + |
| 39 | + const base = Math.floor(count / k); |
| 40 | + const extra = count % k; |
| 41 | + const result = new Array(k).fill(null); |
| 42 | + |
| 43 | + current = head; |
| 44 | + for (let i = 0; i < k && current; i++) { |
| 45 | + result[i] = current; |
| 46 | + const partSize = base + (i < extra ? 1 : 0); |
| 47 | + for (let j = 1; j < partSize; j++) { |
| 48 | + current = current.next; |
| 49 | + } |
| 50 | + const next = current.next; |
| 51 | + current.next = null; |
| 52 | + current = next; |
| 53 | + } |
| 54 | + |
| 55 | + return result; |
| 56 | +}; |
0 commit comments