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 integerx
onto 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.push
calls will not exceed10000
in a single test case. - The total number of
FreqStack.pop
calls will not exceed10000
in a single test case. - The total number of
FreqStack.push
andFreqStack.pop
calls will not exceed150000
across 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 国际许可协议