Skip to content

Latest commit

 

History

History
137 lines (55 loc) · 2.47 KB

File metadata and controls

137 lines (55 loc) · 2.47 KB

中文文档

Description

Implement FreqStack, a class which simulates the operation of a stack-like data structure.

FreqStack has two functions:

    <li><code>push(int x)</code>, which pushes an integer <code>x</code> onto the stack.</li>
    
    <li><code>pop()</code>, which <strong>removes</strong> and returns the most frequent element in the stack.
    
    <ul>
    
    	<li>If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.</li>
    
    </ul>
    
    </li>
    

 

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:

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].

 

Note:

    <li>Calls to <code>FreqStack.push(int x)</code>&nbsp;will be such that <code>0 &lt;= x &lt;= 10^9</code>.</li>
    
    <li>It is guaranteed that <code>FreqStack.pop()</code> won&#39;t be called if the stack has zero elements.</li>
    
    <li>The total number of <code>FreqStack.push</code> calls will not exceed <code>10000</code> in a single test case.</li>
    
    <li>The total number of <code>FreqStack.pop</code>&nbsp;calls will not exceed <code>10000</code> in a single test case.</li>
    
    <li>The total number of <code>FreqStack.push</code> and <code>FreqStack.pop</code> calls will not exceed <code>150000</code> across all test cases.</li>
    

 

Solutions

Python3

Java

...