876. Middle of the Linked List
阿新 • • 發佈:2019-01-26
自我 += 偶數 反思 span 自己 感覺 urn pan
題目來源:
自我感覺難度/真實難度:
題意:
分析:
自己的代碼:
import math class Solution: def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ n=0 head1=head while head1: head1=head1.next n+=1 for i in range(math.ceil(n/2)): head=head.next return head.val
代碼效率/結果:
優秀代碼:
class Solution(object): def middleNode(self, head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
代碼效率/結果:
自己優化後的代碼:
class Solution: defmiddleNode(self, head): """ :type head: ListNode :rtype: ListNode """ fast=slow=head while fast and fast.next: fast=fast.next.next slow=slow.next return slow
反思改進策略:
寫題時間時長:
1.取linked list 中間值,用快慢指針
2.停止的條件是fast.next=none 和fast 一起來判斷,因為fast是對偶數個,fast.next 是 針對奇數個的時候
876. Middle of the Linked List