leetcode-716-Max Stack
问题
Design a max stack that supports push, pop, top, peekMax and popMax.
- push(x) – Push element x onto stack.
- pop() – Remove the element on top of the stack and return it.
- top() – Get the element on the top.
- peekMax() – Retrieve the maximum element in the stack.
- popMax() – Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
Example 1:
1 | MaxStack stack = new MaxStack(); |
Note:
- -1e7 <= x <= 1e7
- Number of operations won’t exceed 10000.
- The last four operations won’t be called when stack is empty.
分析
这道题中一开始没有说清楚,还以为和MinStack那道题类似,直接用两个栈解决即可。后来发现popMax函数只会把栈中最大的元素pop出来,而其他元素还都留在栈中。这样的话就不能使用stack等线性表来实现了,改用双向链表list来实现。然后在通过一个 map\
代码
1 | class MaxStack { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/11/leetcode-716/
License: 知识共享署名-非商业性使用 4.0 国际许可协议