Re: [閒聊] 每日leetcode

作者: argorok (s.green)   2024-09-08 09:24:09
725. Split Linked List in Parts
問題: 給一linked list 要分成k組
思路: 先算出長度n 每組n/k個 有n%k個組會多1個
每次loop 就push每組的頭 讓每組的尾巴=nullptr
class Solution {
public:
vector<ListNode*> splitListToParts(ListNode* head, int k) {
vector<ListNode*> ans;
int n = 0;
ListNode* cur = head;
while(cur != nullptr){
n++;
cur = cur->next;
}
int partSize = n / k, partExtra = n > k ? n % k : 0;
cur = head;
while(ans.size() < k){
ans.push_back(cur);
int steps = ans.size() <= partExtra ? partSize : partSize-1;
while(cur && steps

Links booklink

Contact Us: admin [ a t ] ucptt.com