LeetCode
Guide
C++
Hard
原題連結: https://leetcode.com/problems/maximum-frequency-stack/
Difficulty: Hard
Implement FreqStack, a class which simulates the operation of a stack-like data structure.
FreqStack has two functions:
["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],
[[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
[null,null,null,null,null,null,null,5,7,5,4]
After making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top.
Then:
pop() -> returns 5, as 5 is the most frequent.
The stack becomes [5,7,5,7,4].pop() -> returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top.
The stack becomes [5,7,5,4].pop() -> returns 5.
The stack becomes [5,7,4].pop() -> returns 4.
The stack becomes [5,7].
- Calls to FreqStack.push(int x) will be such that
0 <= 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 exceed
10000
in a single test case.- The total number of FreqStack.pop calls will not exceed
10000
in a single test case.- The total number of FreqStack.push and FreqStack.pop calls will not exceed
150000
across all test cases.
這題的目標是要實作一個類別,其中有兩個函式需完成:
Runtime: 264 ms > faster than 29.98%
Memory: 68.2 MB > less than 100.00%
這題的重點在於以下幾點:
那根據這些考量,我們利用
來記錄次數,而實際上的stack部分,則要巧妙的運用到
拿Example1舉個例子,在經過前面的push之後,理論上stack會是:
[5, 7, 5, 7, 4, 5]
然而,依據我們儲存的方式,實際上會長成這個樣子:
frq:
[4] -> 1
[5] -> 3
[7] -> 2lvl: top = 3
[1] -> {5, 7, 4}
[2] -> {5, 7}
[3] -> {5}
這樣有什麼好處呢?我們接著看。如果現在執行了pop(),此時從lvl中來看,最高次數的最末端是5,所以5會被pop掉,那儲存的樣子就會變成:
frq:
[4] -> 1
[5] -> 2
[7] -> 2lvl: top = 2
[1] -> {5, 7, 4}
[2] -> {5, 7}
一次可能還不明顯,我們再pop一次,這次從lvl中可以發現,最高次數2的那個vector中,存著兩個數,那因為7比較後面,表示7是比較晚被push進來的,所以次數最高且最靠近末端的就會是7,得到以下:
frq:
[4] -> 1
[5] -> 2
[7] -> 1lvl: top = 2
[1] -> {5, 7, 4}
[2] -> {5}
依此類推。如此一來就能把這題給搞定了!