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

[leetcode 155]min stack

时间:2015-02-12 22:35:46      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

1 题目

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.

2 思路

前三个直接调用系统函数即可。c++之类还需要思考一下越界之类的问题。主要实现的是getMin(),要求在常数时间内实现,想了一下,没想出来,搜索,发现可以用空间换时间,新建个最小数的stack就可以了,要注意push时条件是等号。

3 代码

    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> min_stack = new Stack<Integer>();
    public void push(int x) {
        if (stack.isEmpty()) {
            min_stack.push(x);
        }else {
            if (x <= min_stack.peek()) {//小于等于
                min_stack.push(x);
            }
        }
        stack.push(x);
    }

    public void pop() {
        int x = stack.pop();
       if (x == min_stack.peek()) {//相等
        min_stack.pop();
    } 
    }

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

    public int getMin() {
        return min_stack.peek();
    }

 

[leetcode 155]min stack

标签:

原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4288947.html

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