码迷,mamicode.com
首页 > 其他好文 > 详细

Min Stack

时间:2015-03-15 12:05:19      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

  两个栈 一个正常栈,一个用来存储Min值

技术分享
class MinStack {
    private Stack<Integer> normal = new Stack<Integer>();
    private Stack<Integer> min = new Stack<Integer>();
    
    public void push(int x) {
        if(min.isEmpty() || x <= min.peek())
        {
            min.push(x);
        }
        normal.push(x);
    }

    public void pop() {
        int x = normal.pop();
        if(x == min.peek())
        {
           min.pop(); 
        }
    }

    public int top() {
        return normal.peek();
    }

    public int getMin() {
        return min.peek();
    }
}
View Code

 

Min Stack

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4338925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!