895. Maximum Frequency Stack
题目
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the FreqStack class:
FreqStack()constructs an empty frequency stack.void push(int val)pushes an integervalonto the top of the stack.int pop()removes and returns the most frequent element in the stack.- If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
Example 1:
Input ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output [null, null, null, null, null, null, null, 5, 7, 5, 4] Explanation FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is [5] freqStack.push(7); // The stack is [5,7] freqStack.push(5); // The stack is [5,7,5] freqStack.push(7); // The stack is [5,7,5,7] freqStack.push(4); // The stack is [5,7,5,7,4] freqStack.push(5); // The stack is [5,7,5,7,4,5] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].
Constraints:
0 <= val <= 109- At most
2 * 104calls will be made topushandpop. - It is guaranteed that there will be at least one element in the stack before calling
pop.
Related Topics
思路
题目中模拟 frequency stack 时,直观模拟一维数组结构,
内部实现如果采用单一维数组作为数据结构,每次查找处理元素需要对其 frequency 进行排序, 则每次查找效率为 O(nlogn)
对于 Frequency Stack 这种数据模式,我们只需要关心 push 和 pop 操作的返回值,无需关心所有数据的排序
需要优化查找复杂性, 可根据词频进行数据存储, 每次 pop 查找时返回词频最大的数组中的首个元素即可。
注意,词频统计是连续的,不存在跳跃的情况
- 当前最大词频是 8,
- 词频为 8 的元素都被 pop 后, 即
len(self.group[8]) == 0ornot self.group[8] - 则下一个最大词频则是 7
解法
py
# leetcode submit region begin(Prohibit modification and deletion)
from collections import defaultdict
from itertools import count
from typing import List
class FreqStack:
def __init__(self):
self.group = defaultdict(list)
self.count = defaultdict(int)
self.max_freq = 0
def push(self, val: int) -> None:
freq = self.count[val] + 1
self.group[freq].append(val)
self.count[val] = freq
self.max_freq = max(self.max_freq, freq)
def pop(self) -> int:
max_freq_group = self.group[self.max_freq]
val = max_freq_group.pop()
self.count[val] -= 1
if not self.group[self.max_freq]:
self.max_freq -= 1
return val
# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(val)
# param_2 = obj.pop()
# leetcode submit region end(Prohibit modification and deletion)复杂度分析
- 时间复杂度 O(1)
- 空间复杂度 O(N)