跳至主要内容

725. Split Linked List in Parts

Hint

/**
* 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)
{
int n = 0;
ListNode* cur = head;
while (cur)
{
n++;
cur = cur->next;
}

int splitSize = n / k;
int remaining = n % k;

vector<ListNode*> res(k);
cur = head;
for (int i = 0; i < k; i++)
{
ListNode* partHead = cur;
int partSize = splitSize + (remaining > 0 ? 1 : 0);
remaining--;

for (int j = 0; j < partSize - 1 && cur; j++)
{
cur = cur->next;
}

if (cur) {
ListNode* nextPart = cur->next;
cur->next = nullptr;
cur = nextPart;
}
res[i] = (partHead);
}
return res;
}
};
  • T: O(n)O(n)
  • S: O(n)O(n)