Python set + que, actually OrderedDict would do, but maybe less Pythonic


  • 0
    B
    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.que = [i for i in range(maxNumbers)]
            self.numSet = set(self.que)
    
        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
            """
            if not self.que:
                return -1
            result = self.que.pop(0)
            self.numSet.remove(result)
            return result
    
        def check(self, number):
            """
            Check if a number is available or not.
            :type number: int
            :rtype: bool
            """
            return number in self.numSet
    
        def release(self, number):
            """
            Recycle or release a number.
            :type number: int
            :rtype: void
            """
            if number not in self.numSet:
                self.numSet.add(number)
                self.que.append(number)
    
    # 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)
    

  • 0

    @bigoffer4all You only need one set.

    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
    B

    @agave You are right. I thought this question requires getting available numbers in order.


Log in to reply
 

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