725. Split Linked List in Parts

本文详细解析了链表分段算法,针对不同输入情况,如k大于等于链表长度和k小于链表长度,提供了具体的实现思路和代码示例。通过均匀分配链表节点,确保各部分链表的节点数量尽可能均衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/split-linked-list-in-parts/

 

k>=length, 每个部分有且仅有一个,剩下k-length个部分都是空

Input: 
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]

k<length,每个部分至少有length/k个,那么剩下的length%k个就要给每个部分匀一个

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]]

最终有:

前length%k个部分,size为(length/k)+1

剩下的部分size就是length/k

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode[] splitListToParts(ListNode root, int k) {
11         ListNode[] result = new ListNode[k];
12         int length = 0;
13         for (ListNode cursor = root; cursor != null; cursor = cursor.next) {
14             length++;
15         }
16         int perPartNum = length / k;
17         int remainNum = length % k;
18         ListNode head = root;
19         ListNode perPartTail = null;
20         for(int i = 0; i < k; i++, remainNum--){
21             result[i] = head;
22             for(int j = 0; j<perPartNum+(remainNum> 0 ? 1 : 0); j++){
23                 perPartTail = head;
24                 head = head.next;
25             }
26             if(perPartTail != null){
27                 perPartTail.next = null;
28             }
29         }
30         return result;
31     }
32 }
remainNum就是需要匀出去的部分,最开始的几个在分配的时候就会多一个

转载于:https://www.cnblogs.com/TheLaughingMan/p/10155128.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值