题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是要实现一个数据结构,这个结构初始是一个正整数集合,要求能返回集合中的最小值,并随时往集合里加正整数。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class SmallestInfiniteSet:
def __init__(self):
self.heap = [1]
self.rec = set()
heapify(self.heap)

def popSmallest(self) -> int:
# print("pop")
res = heappop(self.heap)
self.rec.add(res)
if len(self.heap) == 0:
heappush(self.heap, res+1)
# print(list(self.heap))
# print(self.rec)
return res

def addBack(self, num: int) -> None:
print(f"add {num}")
if not num in self.rec:
return
heappush(self.heap, num)
self.rec.discard(num)
# print(list(self.heap))
# print(self.rec)


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