Design a data structure that supports the following operations:
push(x): pushes an integerxonto the stackpop(): removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, remove the one closest to the top
Implement the class to support these operations efficiently.
这道题考察的是“高频栈”设计:需要在支持普通入栈的同时,快速弹出当前出现次数最多的元素;如果多个元素频次相同,则优先弹出离栈顶最近的那个。典型做法是用哈希表统计每个元素的出现次数,再用“频次到元素栈”的分组结构记录相同频次下的入栈顺序,同时维护当前最大频次。这样 <code>push</code> 和 <code>pop</code> 都可以做到接近 O(1),非常适合面试中考察数据结构设计与细节处理。
正文完