原题链接在这里:https://leetcode.com/problems/max-stack/description/
题目:
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:
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:
- -1e7 <= x <= 1e7
- Number of operations won't exceed 10000.
- The last four operations won't be called when stack is empty.
题解:
类似Min Stack.
两个stack来解决. 不同的是popMax, 用temp stack 来保存找到最大值之前的, pop出max后再加回去, 同时更新maxStk.
Time Complexity: push, O(1). pop, O(1). top, O(1). peekMax, O(1). popMax, O(n). n是stack中数字的个数.
Space: O(n).
AC Java:
1 class MaxStack { 2 Stack<Integer> stk; 3 Stack<Integer> maxStk; 4 5 /** initialize your data structure here. */ 6 public MaxStack() { 7 stk = new Stack<Integer>(); 8 maxStk = new Stack<Integer>(); 9 } 10 11 public void push(int x) { 12 stk.push(x); 13 if(maxStk.isEmpty() || maxStk.peek()<=x){ 14 maxStk.push(x); 15 } 16 } 17 18 public int pop() { 19 int x = stk.pop(); 20 if(!maxStk.isEmpty() && x==maxStk.peek()){ 21 maxStk.pop(); 22 } 23 24 return x; 25 } 26 27 public int top() { 28 return stk.peek(); 29 } 30 31 public int peekMax() { 32 return maxStk.peek(); 33 } 34 35 public int popMax() { 36 Stack<Integer> tempStk = new Stack<Integer>(); 37 int x = maxStk.pop(); 38 while(!stk.isEmpty() && stk.peek()<x){ 39 tempStk.push(stk.pop()); 40 } 41 42 stk.pop(); 43 while(!tempStk.isEmpty()){ 44 int top = tempStk.pop(); 45 push(top); 46 } 47 return x; 48 } 49 } 50 51 /** 52 * Your MaxStack object will be instantiated and called as such: 53 * MaxStack obj = new MaxStack(); 54 * obj.push(x); 55 * int param_2 = obj.pop(); 56 * int param_3 = obj.top(); 57 * int param_4 = obj.peekMax(); 58 * int param_5 = obj.popMax(); 59 */