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