上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* head, int k) {
}
};
golang 解法, 执行用时: 0 ms, 内存消耗: 2.8 MB, 提交时间: 2021-09-22 16:35:11
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func splitListToParts(head *ListNode, k int) []*ListNode {
n := 0
for node := head; node != nil; node = node.Next {
n++
}
quotient, remainder := n/k, n%k
parts := make([]*ListNode, k)
for i, curr := 0, head; i < k && curr != nil; i++ {
parts[i] = curr
partSize := quotient
if i < remainder {
partSize++
}
for j := 1; j < partSize; j++ {
curr = curr.Next
}
curr, curr.Next = curr.Next, nil
}
return parts
}