Re: [閒聊] 每日leetcode

看板Marginalman作者 (enmeitiryous)時間1年前 (2024/09/08 23:34), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串827/1548 (看更多)
題目: 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--; } ListNode* thend=cur; if(cur){ cur=cur->next; } if(thend){ thend->next=nullptr; } } return ans; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.227.226.5 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725809676.A.A58.html
文章代碼(AID): #1ctSGCfO (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ctSGCfO (Marginalman)