Skip to content

Commit 6e9ec14

Browse files
authored
Create smallest-number-in-infinite-set.py
1 parent 83ac43c commit 6e9ec14

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: ctor: O(1)
2+
# popSmallest: O(logn)
3+
# addBack: O(logn)
4+
# Space: O(n)
5+
6+
import heapq
7+
8+
9+
# heap
10+
class SmallestInfiniteSet(object):
11+
12+
def __init__(self):
13+
self.__n = 1
14+
self.__lookup = set()
15+
self.__min_heap = []
16+
17+
def popSmallest(self):
18+
"""
19+
:rtype: int
20+
"""
21+
if self.__min_heap:
22+
result = heapq.heappop(self.__min_heap)
23+
self.__lookup.remove(result)
24+
return result
25+
result = self.__n
26+
self.__n += 1
27+
return result
28+
29+
def addBack(self, num):
30+
"""
31+
:type num: int
32+
:rtype: None
33+
"""
34+
if num >= self.__n or num in self.__lookup:
35+
return
36+
self.__lookup.add(num)
37+
heapq.heappush(self.__min_heap, num)

0 commit comments

Comments
 (0)