[LeetCode] Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

分析:用两个栈来实现

 1 class MinStack {
 2     // normal stack
 3     Stack<Integer> st = new Stack<Integer>();
 4     // min value stack
 5     Stack<Integer> stm = new Stack<Integer>();
 6     
 7     public void push(int x) {
 8         st.push(x);
 9         if (stm.isEmpty() || stm.peek() >= x)
10             stm.push(x);
11     }
12 
13     public void pop() {
14         int peek = st.peek();
15         st.pop();
16         if (peek <= stm.peek())
17             stm.pop();
18     }
19 
20     public int top() {
21         return st.peek();
22     }
23 
24     public int getMin() {
25         return stm.peek();
26     }
27 }

 

posted @ 2015-11-07 15:49  Tony-Hu  阅读(216)  评论(0编辑  收藏  举报