LC.P725[分隔链表]

方法一:模拟

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode[] splitListToParts(ListNode head, int k) {
ListNode p = head;
int n = 0;
while (p != null) {
p = p.next;
++n;
}
ListNode[] ans = new ListNode[k];
int groupSize = n / k, reminder = n % k;
ListNode cur = head;
for (int i = 0; i < k && cur != null; ++i) {
ans[i] = cur;
int partSize = groupSize + (i < reminder ? 1 : 0);
for (int j = 1; j < partSize; ++j) {
cur = cur.next;
}
ListNode next = cur.next;
cur.next = null;
cur = next;
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$