LeetCode題解(Offer22):尋找連結串列中倒數第k個節點(Python)

長行發表於2020-10-01

題目:原題連結(簡單)

標籤:連結串列、雙指標

解法時間複雜度空間複雜度執行用時
Ans 1 (Python) O ( 2 × N − K ) O(2×N-K) O(2×NK) = O ( N ) O(N) O(N) O ( 1 ) O(1) O(1)52ms (14.13%)
Ans 2 (Python) O ( N ) O(N) O(N) O ( N ) O(N) O(N)40ms (80.30%)
Ans 3 (Python)

解法一(雙指標):

class Solution:
    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
        slow = fast = head
        for i in range(k):
            fast = fast.next
        while fast:
            fast = fast.next
            slow = slow.next
        return slow

解法二(轉換為列表):

class Solution:
    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
        lst = []
        while head:
            lst.append(head)
            head = head.next
        return lst[-k]

相關文章