2130. 連結串列最大孿生和

WrRan發表於2024-09-12
題目連結 2130. 連結串列最大孿生和
思路 連結串列綜合題:快慢指標 + 指標翻轉
題解連結 官方題解
關鍵點 while fast.next and fast.next.next: ...
時間複雜度 \(O(n)\)
空間複雜度 \(O(1)\)

程式碼實現:

class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        if head is None:
            return 0
        first = self.halfList(head)
        second = self.reverseList(first.next)

        answer = 0
        while second:
            answer = max(answer, head.val + second.val)
            head = head.next
            second = second.next
        return answer
    
    def halfList(self, head):
        slow = fast = head
        while fast.next and fast.next.next:
            fast = fast.next.next
            slow = slow.next
        return slow
    
    def reverseList(self, head):
        previous = None
        current = head
        while current:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node
        return previous

相關文章