What wrong with this?


  • 0
    T

    What wrong with my solution?
    It failed on the last test but it's correcr

    class LL(object):
        def __init__(self,val):
            self.next = self
            self.prev = self
            self.val = val
        
        def insertAfter(self,el):
            self.prev = el
            self.next = el.next
            el.next.prev = self
            el.next = self
            
        
        def remove(self):
            self.prev.next = self.next
            self.next.prev = self.prev
    
    class RandomizedCollection(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.head = LL(-1)
            self.h = {}
    
        def insert(self, val):
            """
            Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
            :type val: int
            :rtype: bool
            """
            ret = False
            el = LL(val)
            el.insertAfter(self.head)
                
            if not val in self.h:
                self.h[val] = []
                ret = True
            self.h[val].append(el)
            return ret
            
    
        def remove(self, val):
            """
            Removes a value from the collection. Returns true if the collection contained the specified element.
            :type val: int
            :rtype: bool
            """
            if val in self.h and self.h[val]:
                ret = self.h[val].pop()
                ret.remove()
                return True
            return False
    
        def getRandom(self):
            """
            Get a random element from the collection.
            :rtype: int
            """
            el = self.head.prev
            el.remove()
            el.insertAfter(self.head)
            return el.val
            
    
    
    # Your RandomizedCollection object will be instantiated and called as such:
    # obj = RandomizedCollection()
    # param_1 = obj.insert(val)
    # param_2 = obj.remove(val)
    # param_3 = obj.getRandom()
    

Log in to reply
 

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