码迷,mamicode.com
首页 > 编程语言 > 详细

Java [Leetcode 155]Min Stack

时间:2016-02-22 11:58:48      阅读:148      评论: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.

解题思路:

主要是怎么保存最小值这个问题,每次在向栈中添加数据时,总是和当前的最小值比较,如果比当前的最小值小,那么则把当前的最小值压入栈中,表明当前栈中的最小值为当前最小值,然后再把新的数据压入栈中。每次弹出栈顶的元素时候,将弹出的数据与当前的最小值比较,如果相等,表明已经达到当前最小值所在的位置,下面的那个数是当前栈中的最小值,将其弹出,其值为新的最小值。

代码如下:

class MinStack {
    
	Stack<Integer> stack = new Stack<Integer>();
	int min = Integer.MAX_VALUE;
	
    public void push(int x) {
    	if(x <= min){
    		stack.push(min);
    		min = x;
    	}
    	stack.push(x);
    }    

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

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

    public int getMin() {
        return min;
    }
}

  

Java [Leetcode 155]Min Stack

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5206417.html

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