Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2023-09-06 15:05:53
https://leetcode.com/problems/split-linked-list-in-parts/description/
725. Split Linked List in Parts
给你一个连结串行 head 和一个数字 k,我们要把该串行切成 k 个部分,并且
每个部分都要满足条件:
1.每个部分的大小相差不超过一,例如:[1][2][3] 或 [1,2][3]
2.前面部分大小必须大于等于后面,例如:[1,2,3][4,5,6,7] 不行因为后面比较大
3.必须按照切分前的原始顺序排列
Example 1:
https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg
Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but its string representation as a
ListNode is [].
Example 2:
https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg
Input: head = [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.
思路:
1.先算出串行共有几个元素,然后用 size 算出 node 分成k等分之后会多出几个,这些
多的都先给前面的,就可以找出每个阵列里面共有几个元素。
2.再遍历一次串行并抓出每个部分的head加入到结果集,每次加完一部分就把前个node的
next砍断。
3.返回结果集。
Java Code:
作者: JerryChungYC (JerryChung)   2023-09-06 15:18:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com