General solution, 55ms Python


  • 0
    Y

    It is a solution without the consideration of the sorted condition

    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        value_store = {}
        curr = head
        pre = None
        while curr:
            if curr.val in value_store:
                pre.next = curr.next
            else:
                value_store.setdefault(curr.val)
                pre = curr
            curr = curr.next
        return head

  • 0
    S

    why not using set


  • 0
    Y

    @shi-xiaopeng

    Hi.
    I think set can't be used in linked list. Because we only return the head.
    Normally, I prefer using hash table and I don't use set too much. So I choose hash table in this question.
    And I have tried the set way, but I met a error:

    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        value_store = set()
        curr = head
        pre = None
        while curr:
            value_store.update(curr.val)
            pre = curr
            curr = curr.next
        return head
    

    Runtime Error Message:
    Line 17: TypeError: 'int' object is not iterable
    Last executed input:[1]

    And would you mind uploading your solution of set? Thank you


  • 0
    S

    Your solution is good enough. say 'why not using set' means Using set as the container, since set is more simple and efficient than dict.

    value_store = set()
    ...
    else:
        value_store.add(curr.val)
        ...
    

    just need change 2 lines showing above. using set to remove duplicate will lose the order


  • 0
    Y

    @shi-xiaopeng

    Thanks :). And I'll use set more


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.