一、题目
设计一个类似堆栈的数据结构,将元素推入堆栈,并从堆栈中弹出出现频率最高的元素。
实现 FreqStack 类:
FreqStack() 构造一个空的堆栈。
void push(int val) 将一个整数 val 压入栈顶。
int pop() 删除并返回堆栈中出现频率最高的元素。
如果出现频率最高的元素不只一个,则移除并返回最接近栈顶的元素。
二、思路
频率其实就是计数,计数最先想到的应该是哈希。
① 首先通过一个哈希表,计算每个入栈元素出现的次数(入栈和出站的时候对应元素 加一或减一即可)
② 找到频率最高为多少
③ 从栈顶开始寻找出现频率最高的位置
入栈:
首先元素入栈,然后更新上述的①和②,然后更新③
出栈:
首先弹出 频率最高的位置 的数,然后更新①和②,然后更新③
三、代码
代码如下:
1.方法一
class FreqStack:
def __init__(self):
self.dic = {}
self.stack = []
self.max_ = 0
def push(self, val: int) -> None:
self.stack.append(val)
self.dic[val] = self.dic.get( val , 0 ) + 1
# self.max_ = self.max_val()
self.max_ = max(self.dic.values())
# print(self.max_)
self.idx = self.sor()
def pop(self) -> int:
# print(self.stack, self.idx)
res = self.stack.pop(self.idx)
self.dic[res] = self.dic.get( res , 0 ) - 1
self.max_ = max(self.dic.values())
self.idx = self.sor()
return res
def sor(self):
for i in range(len(self.stack)-1,-1,-1):
if self.dic[self.stack[i]] == self.max_:
return i
return 0
# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(val)
# param_2 = obj.pop()