Re: [閒聊] 每日LeetCode

看板Marginalman作者 (麵包屌)時間3年前 (2022/12/05 23:10), 編輯推噓3(302)
留言5則, 4人參與, 3年前最新討論串127/719 (看更多)
876. Middle of the Linked List 給你一個 linked list 的 head node,要你回傳它正中間的 node 如果長度是偶數就回傳靠後的那個 Example 1: Input: head = [1,2,3,4,5] Output: [3,4,5] (回傳 3 那個 node) Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] (回傳 4 那個 node) 思路: 1. linked list 題目中 fast/slow node 的最基本型 讓 fast, slow 都從 head 開始 每次讓 fast = fast.next.next, slow = slow.next 就可以在 fast 走到最尾端時讓 slow 在正中間 2. Python code: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next return slow -- 蛤? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.204.64 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1670253030.A.047.html

12/05 23:11, 3年前 , 1F
大師
12/05 23:11, 1F

12/05 23:14, 3年前 , 2F
大師
12/05 23:14, 2F

12/05 23:14, 3年前 , 3F
學到了
12/05 23:14, 3F

12/05 23:35, 3年前 , 4F
學到了
12/05 23:35, 4F

12/05 23:42, 3年前 , 5F
大師
12/05 23:42, 5F
文章代碼(AID): #1ZZWdc17 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZZWdc17 (Marginalman)