簡體   English   中英

刪除鏈表中所有重復的元素

[英]Removing all repeated elements in a linked list

給定一個已排序的鏈表,請刪除所有具有重復編號的節點,只保留原始列表中不同的編號。

范例1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

范例2:

Input: 1->1->1->2->3
Output: 2->3

在大多數情況下,我已經嘗試並成功完成了代碼,唯一缺少的情況是列表以重復結尾,並且整個過程中都沒有重復。

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        first = head
        if first is None:
            return []
        second = head.next
        if second is None:
            return first
        first.next = second
        if first.val == first.next.val:
            while first.val == first.next.val:
                if first.next.next is None:
                    return []
                first = first.next
            return self.deleteDuplicates(first.next)
        else:
            first.next = self.deleteDuplicates(first.next)
            return first

對於[1,2,3,4,4],我得到的錯誤是“ AttributeError:'list'對象沒有屬性'val'”。

您可以在$ O(n)$的時間和$ O(n)$的空間(最壞的情況下)中進行此操作,只需跟蹤您到目前為止所看到的內容即可,前提是您的數據是可哈希的。

from collections import defaultdict

def mark_duplicates(current_node, seen_so_far):
    next = current_node.next
    seen_so_far[current_node.data] += 1
    if next is None: return seen_so_far
    return mark_duplicates(next, seen_so_far)

def remove_duplicates(current_node, seen):
    next = current_node.next
    prev = current_node.prev
    if seen[current_node.data] > 1:
        if prev is not None: prev.next = next
        if next is not None: next.prev = prev
        # No need to delete current_node, the GC will do it
    if next is not None: remove_duplicates(next, seen)

notes = mark_duplicates(head_of_list, defaultdict(int))
remove_duplicates(head_of_list, notes)

defaultdict(int)只是一個字典,當您嘗試訪問不存在的鍵時將返回0。 因此,此操作會計算每個值出現多少次,然后刪除多次顯示的所有內容。

代碼工作正常,我只需要將return []更改為簡單的“ return”,因為[]未被識別為空鏈表,而是一個空列表。 感謝Devesh Kumar Singh識別此錯誤,但他沒有將其發布為答案,因此我代表他進行了發布。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM