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