Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤10^5^). Then N lines follow, each contains a command in one of the following 3 formats:
1 | Push key |
where key
is a positive integer no more than 10^5^.
Output Specification:
For each Push
command, insert key
into the stack and output nothing. For each Pop
or PeekMedian
command, print in a line the corresponding returned value. If the command is invalid, print Invalid
instead.
Sample Input:
1 | 17 |
Sample Output:
1 | Invalid |
浅析
Q:在普通栈的基础上加上查询中位数的功能。
普通栈用 stack 头文件可快速实现。考虑到数字比较多,中位数用哈希表实现,重写 Push 和 Pop 来实现出入栈的同时哈希表的维护。
Code
1 |
|