思路
push时,根据 most freq 找到符合这个 freq 的 x (x保存在数组里,数组长度>= 1),再根据后进后出 pop x
如何快速得到most freq?用一个变量保存most freq的值
如何维护 most freq?利用每次只能 push “一个” 元素的特性,每次 push 检查 x 的 freq 是否是 most freq
如何快速查找x的freq? 用 hash 保存 x 对应的freq, key: x, value: freq
如何保证 pop 时后进后出? 再用一个 hash,保存每个 freq 对应的 x 们,key: freq, value: [x1, x2 ..]
Time: push pop 都是 O(1) Space: O(n)
代码
import collections
class FreqStack(object):
def __init__(self):
self.freq = collections.Counter() # map x -> freq of x, keep track of the freq of each x
self.data = collections.defaultdict(list) # map freq -> [x1, x2 ...], ensure the order when poping
self.maxfreq = 0
def push(self, x):
"""
:type x: int
:rtype: None
"""
# keep track of freq of x
self.freq[x] += 1
# maintain maxfreq
self.maxfreq = max(self.maxfreq, self.freq[x])
self.data[self.freq[x]].append(x)
def pop(self):
"""
:rtype: int
"""
x = self.data[self.maxfreq].pop()
self.freq[x] -= 1
# maintain maxfreq
if self.data[self.maxfreq] == []:
self.maxfreq -= 1
return x
# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(x)
# param_2 = obj.pop()