Re: [閒聊] 每日leetcode

作者: enmeitiryous (enmeitiryous)   2024-09-08 23:34:34
題目: 725. split linklist in parts
給你一個linklist請將他盡量等分成k份,除非相鄰為空則相鄰彼此長度差小於一
思路:
先記錄長度後,依照len/k去分配並且若為前len%k個,則若當前長度<len/k+1則
允許再塞一個再更新當前指標到下一個點並更新該位置的next指向nullptr
int check_len(ListNode* head){
ListNode* cur=head;
int ans=0;
while(cur){
++ans;
cur=cur->next;
}
return ans;
}
vector<ListNode*> splitListToParts(ListNode* head, int k) {
int prelen=check_len(head);
int turlen=prelen/k;
int cring=prelen%k;
vector<ListNode*> ans;
ListNode* cur=head;
while(ans.size()<k){
int nolen=1;
ans.push_back(cur);
while(cur && nolen<turlen){
cur=cur->next;
nolen++;
}
if(cur && cring>0){
if(nolen<turlen+1){
cur=cur->next;
}
cring

Links booklink

Contact Us: admin [ a t ] ucptt.com