-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path725.分隔链表.cs
117 lines (115 loc) · 3 KB
/
725.分隔链表.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* @lc app=leetcode.cn id=725 lang=csharp
*
* [725] 分隔链表
*
* https://leetcode-cn.com/problems/split-linked-list-in-parts/description/
*
* algorithms
* Medium (49.71%)
* Likes: 25
* Dislikes: 0
* Total Accepted: 2.3K
* Total Submissions: 4.7K
* Testcase Example: '[1,2,3,4]\n5'
*
* 给定一个头结点为 root 的链表, 编写一个函数以将链表分隔为 k 个连续的部分。
*
* 每部分的长度应该尽可能的相等: 任意两部分的长度差距不能超过 1,也就是说可能有些部分为 null。
*
* 这k个部分应该按照在链表中出现的顺序进行输出,并且排在前面的部分的长度应该大于或等于后面的长度。
*
* 返回一个符合上述规则的链表的列表。
*
* 举例: 1->2->3->4, k = 5 // 5 结果 [ [1], [2], [3], [4], null ]
*
* 示例 1:
*
*
* 输入:
* root = [1, 2, 3], k = 5
* 输出: [[1],[2],[3],[],[]]
* 解释:
* 输入输出各部分都应该是链表,而不是数组。
* 例如, 输入的结点 root 的 val= 1, root.next.val = 2, \root.next.next.val = 3, 且
* root.next.next.next = null。
* 第一个输出 output[0] 是 output[0].val = 1, output[0].next = null。
* 最后一个元素 output[4] 为 null, 它代表了最后一个部分为空链表。
*
*
* 示例 2:
*
*
* 输入:
* root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
* 输出: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
* 解释:
* 输入被分成了几个连续的部分,并且每部分的长度相差不超过1.前面部分的长度大于等于后面部分的长度。
*
*
*
*
* 提示:
*
*
* root 的长度范围: [0, 1000].
* 输入的每个节点的大小范围:[0, 999].
* k 的取值范围: [1, 50].
*
*
*
*
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode[] SplitListToParts(ListNode root, int k) {
int totalCount = this.count(root);
int perCount = totalCount / k;
int additionalCount = totalCount % k;
ListNode[] result = new ListNode[k];
int index = 0;
while(root != null)
{
if(index < additionalCount)
{
result[index] = root;
root = this.goThrough(root, perCount+1);
}
else
{
result[index] = root;
root = this.goThrough(root, perCount);
}
index++;
}
return result;
}
private int count(ListNode node)
{
int cnt = 0;
while(node!=null)
{
node = node.next;
cnt++;
}
return cnt;
}
private ListNode goThrough(ListNode node, int cnt)
{
while(cnt > 1)
{
node = node.next;
cnt--;
}
ListNode result = node.next;
node.next = null;
return result;
}
}