本文主要是介绍Split Linked List in Parts问题及解法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
Given a (singly) linked list with head node root
, write a function to split the linked list into k
consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode's representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ] 示例:
Input: root = [1, 2, 3], k = 5 Output: [[1],[2],[3],[],[]] Explanation: The input and each element of the output are ListNodes, not arrays. For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null. The first element output[0] has output[0].val = 1, output[0].next = null. The last element output[4] is null, but it's string representation as a ListNode is [].
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]] Explanation: The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
问题分析:
对于此题可转化位整除和求余数的数学问题,也算是求一个分割吧。
举一个例子:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3我们知道root的长度n = 10,那么余数t = 10 % 3 = 1,商s = 10 / 3 = 3.
由此我们可知结果数组res的size = 3,每一个元素的列表长度为4,3,3.
然后依次从左向右遍历root,取对应个数的节点组成新的列表即可。
过程详见代码:
class Solution {
public:vector<ListNode*> splitListToParts(ListNode* root, int k) {vector<ListNode*> res(k,nullptr);vector<ListNode*> p(k, nullptr);int n = 0;ListNode* r = root;while (r){n++;r = r->next;}int s, t;s = n / k;t = n % k;r = root;int count = 0;for (int i = 0; i < k; i++){int ts = s;while (r && ts){if (!res[i]){res[i] = r;}else p[i]->next = r;p[i] = r;r = r->next;ts--;}if (t){if (!res[i]){res[i] = r;}else{p[i]->next = r;}p[i] = r;t--;r = r->next;}if (p[i]) p[i]->next = nullptr;}return res;}
};
这篇关于Split Linked List in Parts问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!