Re: [閒聊] 每日leetcode

看板Marginalman作者 (JerryChung)時間1年前 (2024/09/09 01:56), 編輯推噓0(001)
留言1則, 1人參與, 1年前最新討論串828/1548 (看更多)
※ 引述《dont (dont)》之銘言: : 725. Split Linked List in Parts : ## 思路 : 先計算node的數量, : 除k得到每堆的node數量, 剩下的餘數平均給前r堆 偷懶直接看思路 ListNode真的不懂所以跑去問了ChatGPT 原來 current = head 之後用 current = current.next 不會影響到 head 第一次知道 Python Code: class Solution: def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]: count = 0 ptr = head while ptr: count += 1 ptr = ptr.next part_length, extra = divmod(count, k) parts = [] current = head for i in range(k): current_part_length = part_length + (1 if i < extra else 0) new_head = new_current = None while current_part_length > 0 and current: new_node = ListNode(current.val) if new_head is None: new_head = new_node new_current = new_head else: new_current.next = new_node new_current = new_node current = current.next current_part_length -= 1 parts.append(new_head) return parts 比大師的程式碼長好多 哀 https://i.imgur.com/kYDRjbm.png
1 2 還在放棄狀態沒打到 前天有看題目但不會就放到忘了 再漏一天就不用買票補了 好耶 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.26.206 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725818219.A.E66.html

09/09 01:57, 1年前 , 1F
問GPT有沒有更好的解法 結果它只幫我改變數名 哀
09/09 01:57, 1F
文章代碼(AID): #1ctULhvc (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ctULhvc (Marginalman)