-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path895.py
More file actions
39 lines (33 loc) · 1.1 KB
/
895.py
File metadata and controls
39 lines (33 loc) · 1.1 KB
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
31
32
33
34
35
36
37
38
39
import collections
class FreqStack:
def __init__(self):
self.counter = dict() # key: 数字 value: 频率
self.index_list = collections.defaultdict(list)
self.max_freq = 0
def push(self, x: int) -> None:
freq = None
if x in self.counter:
self.counter[x] += 1
freq = self.counter[x]
else:
freq = 1
self.counter[x] = freq
if freq > self.max_freq:
self.max_freq = freq
self.index_list[freq].append(x)
def pop(self) -> int:
# print(self.counter, self.index_list)
# 找到最大频率值
max_freq = self.max_freq
# 从栈中找到最近的最大频率数
x = self.index_list[max_freq].pop()
self.counter[x] -=1
if not self.index_list[max_freq]:
# 这个频率为空的时候,删除对应的列表
# del self.index_list[max_freq]
self.max_freq -=1
return x
# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(x)
# param_2 = obj.pop()