*379. Design Phone Directory

https://leetcode.com/problems/design-phone-directory/

solution

from heapq import heappop, heappush

class PhoneDirectory:
    def __init__(self, maxNumbers: int):
        self.used = set()  # 记录已被使用的编号
        self.heap = []  # 按照号码的值由小到大进行分配
        self.next = 0
        self.k = maxNumbers  # 电话目录的最大编号

    def get(self) -> int:
        ans = -1
        if len(self.used) == self.k:
            return ans
        if self.heap:
            ans = heappop(self.heap)
        else:
            ans, self.next = self.next, self.next+1
        self.used.add(ans)
        return ans        

    def check(self, n: int) -> bool:
        return n < self.k and n not in self.used

    def release(self, n: int):
        if n in self.used:
            self.used.remove(n)
            heappush(self.heap, n)

时间复杂度:O() 空间复杂度:O()

Last updated