leetcode-895-Maximum Frequency Stack
问题
Implement FreqStack, a class which simulates the operation of a stack-like data structure.
FreqStack has two functions:
push(int x), which pushes an integerxonto the stack.pop(), which removes and returns the most frequent element in the stack. (If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.)
Example 1:
1 | Input: |
Note:
- Calls to
FreqStack.push(int x)will be such that0 <= x <= 10^9. - It is guaranteed that
FreqStack.pop()won’t be called if the stack has zero elements. - The total number of
FreqStack.pushcalls will not exceed10000in a single test case. - The total number of
FreqStack.popcalls will not exceed10000in a single test case. - The total number of
FreqStack.pushandFreqStack.popcalls will not exceed150000across all test cases.
分析
思路1: 使用set<tuple<int,int,int>> st三元组分别保存频率、最后一个数的时间戳、还有这个数的值。在使用unordered_map <int, stack<int>> mp,保存val依次出现的时间戳。push时,如果该元素出现过,并且还在“栈”中,则将其从st中删除,更新频率、最后一个时间戳之后再插入到st中,同时更新对应的mp。pop时,st中最有一个三元组中的val就是要返回的val,将其从st中删除,同时将val对应的栈的栈顶出栈,最后更新频率、时间戳再插入到st中。push时间复杂度O(logn),pop时间复杂度O(logn)。
思路2: unordered_map <int, stack<int>>freq 保存每个数出现的频率,unordered_map <int, stack<int>>m 保存每个频率下一次出现的数组。比如一个数val出现了n次,那么val会出现在栈m[1],m[2],m[3]...m[n] 中。
代码1
1 | // push: O(logn) pop: O(logn) |
代码2
1 | // push: O(1) pop: O(1) |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/14/leetcode-895/
License: 知识共享署名-非商业性使用 4.0 国际许可协议