[leetcode]716. 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.

Example 1:

MaxStack stack = new MaxStack();
stack.push(5); 
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
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.

题目

思路

1.  maintain stack to track all the data 

2. maintain maxStack to update current max, making sure that stack.size() == maxStack.size()

3. when popMax(), use tempStack to convert data. When push data back to stack, don't forget to update maxStack at the same time. 

           

         

code

 1 class MaxStack {
 2     // maintain stack to track all the data 
 3        Stack <Integer> stack  =  new Stack<Integer>();
 4     // maintain maxStack to update current max 
 5     Stack <Integer> maxStack  =  new Stack<Integer>();
 6     
 7     public void push(int x) {
 8         // 保证stack和maxStack的元素数量一致, 即便 x == maxStack.peek(), 也会同时push到maxStack和stack
 9         if (maxStack.isEmpty() || x >= maxStack.peek()){  
10                 maxStack.push(x);
11         }
12         stack.push(x); 
13     }
14      
15     public int pop() {
16        if (stack.peek().equals(maxStack.peek())){
17                    maxStack.pop();
18        }
19        return stack.pop();
20     }
21     
22     public int top() {
23         return stack.peek(); 
24     }
25     
26     public int peekMax() {
27         return maxStack.peek();
28     }
29     
30     public int popMax() {
31             // maintain a tempStack to help convert data 
32             Stack <Integer> tempStack  =  new Stack<Integer>();
33             
34             int max  = maxStack.peek(); 
35             // 1. push non-max item into tempStack 
36             while (!stack.peek().equals(maxStack.peek())){
37                  tempStack.push(stack.pop());
38             }
39             stack.pop();
40             maxStack.pop();
41             
42             //2. directly use push() we wrote, pushing items back in both stack and tempStack 
43             while(!tempStack.isEmpty()){ 
44                     push(tempStack.pop());      
45             }
46             return max;
47     }
48 }
原文地址:https://www.cnblogs.com/liuliu5151/p/9828162.html