Super easy Python solution using dictionary (one line each method)


  • 0
    W
    class PhoneDirectory(object):
    
        def __init__(self, maxNumbers):
            """
            Initialize your data structure here
            @param maxNumbers - The maximum numbers that can be stored in the phone directory.
            :type maxNumbers: int
            """
            self.directory = {i:1 for i in range(maxNumbers)}
            
    
        def get(self):
            """
            Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available.
            :rtype: int
            """
            # popitem(): Remove and return an arbitrary (key, value) pair from the dictionary.
            # if the dictionary is empty, calling popitem() raises a KeyError.
            
            return self.directory.popitem()[0] if self.directory else -1
            
    
        def check(self, number):
            """
            Check if a number is available or not.
            :type number: int
            :rtype: bool
            """
            return number in self.directory
            
    
        def release(self, number):
            """
            Recycle or release a number.
            :type number: int
            :rtype: void
            """
            self.directory[number] = 1
            
    
    # AC: 136ms
    
    # Your PhoneDirectory object will be instantiated and called as such:
    # obj = PhoneDirectory(maxNumbers)
    # param_1 = obj.get()
    # param_2 = obj.check(number)
    # obj.release(number)
    

  • 1

    @WKVictor why not using a set to make your life easier? :)

    class PhoneDirectory(object):
    
        def __init__(self, maxNumbers):
            self.available = set(range(maxNumbers))
    
        def get(self):
            return -1 if not self.available else self.available.pop()
    
        def check(self, number):
            return number in self.available
    
        def release(self, number):
            self.available.add(number)
    

  • 0
    W

    @agave You are absolutely right. set also uses hashing and we do not need to store values, so set is clearly a better choice. Really learned a lot from your solutions. Thanks, man!


Log in to reply
 

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