포스트

[leetcode] Smallest Number in Infinite Set -> heap

  • SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.
  • int popSmallest() Removes and returns the smallest integer contained in the infinite set.
  • void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class SmallestInfiniteSet:

    def __init__(self):
        self.heap= [x for x in range(1, 1001)]

    def popSmallest(self) -> int:
        if self.heap:
            return heapq.heappop(self.heap)
        else:
            return None

    def addBack(self, num: int) -> None:
        if num not in self.heap:
            heapq.heappush(self.heap, num)


# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num)

#leetcode, #heap, #min_heap

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.