项目作者: eMahtab

项目描述 :
Max Stack
高级语言:
项目地址: git://github.com/eMahtab/max-stack.git
创建时间: 2020-02-21T05:05:40Z
项目社区:https://github.com/eMahtab/max-stack

开源协议:

下载


Max Stack

https://leetcode.com/problems/max-stack

Design a max stack that supports push, pop, top, peekMax and popMax.

  1. push(x) — Push element x onto stack.
  2. pop() — Remove the element on top of the stack and return it.
  3. top() — Get the element on the top.
  4. peekMax() — Retrieve the maximum element in the stack.
  5. 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.
  1. Example 1:
  2. MaxStack stack = new MaxStack();
  3. stack.push(5);
  4. stack.push(1);
  5. stack.push(5);
  6. stack.top(); -> 5
  7. stack.popMax(); -> 5
  8. stack.top(); -> 1
  9. stack.peekMax(); -> 5
  10. stack.pop(); -> 1
  11. stack.top(); -> 5

Note:

  1. -1e7 <= x <= 1e7
  2. Number of operations won’t exceed 10000.
  3. The last four operations won’t be called when stack is empty.

Implementation :

  1. class MaxStack {
  2. Stack<Integer> stack = new Stack<>();
  3. Stack<Integer> maxStack = new Stack<>();;
  4. public void push(int x) {
  5. int max = maxStack.isEmpty() ? x : maxStack.peek();
  6. maxStack.push(max > x ? max : x);
  7. stack.push(x);
  8. }
  9. public int pop() {
  10. maxStack.pop();
  11. return stack.pop();
  12. }
  13. public int top() {
  14. return stack.peek();
  15. }
  16. public int peekMax() {
  17. return maxStack.peek();
  18. }
  19. public int popMax() {
  20. int max = peekMax();
  21. Stack<Integer> buffer = new Stack();
  22. while (top() != max) buffer.push(pop());
  23. pop();
  24. while (!buffer.isEmpty()) push(buffer.pop());
  25. return max;
  26. }
  27. }

Key points :

  1. In push(x) operation we push the element to both main stack and maxStack
  2. For popMax(), we know what the current maximum is using peekMax(). We can pop from the main stack until we find that maximum, then push the popped elements back on the main stack.

References :

https://leetcode.com/articles/max-stack