首页 > 其他 > 详细

[LeetCode] Min Stack

时间:2015-11-07 17:26:00      阅读:166      评论:0      收藏:0      [点我收藏+]

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 }

 

[LeetCode] Min Stack

原文:http://www.cnblogs.com/tonyhu1993/p/4945337.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!