155. Min Stack

来源:互联网 发布:百度seo排名点击软件 编辑:程序博客网 时间:2024/05/11 12:32

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 thestack.

top() -- Get the top element.

getMin() -- Retrieve the minimum element inthe stack.

翻译:设计一个支持push,pop,top和在一定时间内检索最小元素的堆栈。

push(x) - 将元素x推到堆栈上。

pop() - 删除堆栈顶部的元素。

top() - 获取顶部元素。

getMin() - 检索堆栈中的最小元素。

分析:主要是能够直接求得最小值,参考了一下别人的解答思路:

1、栈初始化

stack =new Stack();

2、入栈

若栈空,将0压入栈中;同时设置最小值,将min=x;

若栈不为空,则将top-min,如果top<min,重新将min=top;

3、出栈

若栈为空,return;

若栈不为空,直接出栈(不考虑将值保存起来),如果栈顶元素小于0,证明这个元素就是最小元素放进去的,重新将最小值赋值,min=min-top

4、获得栈顶元素

直接获得栈顶元素,使用peek(),如果top>0,返回top+min

否则返回最小值min

5、获得栈的最小值

直接返回最小值

有一个问题就是需要转换成long类型

public class MinStack {

   long min;

   Stack<Long> stack;

 

   /** initialize your data structure here. */

   public MinStack() {

       stack=new Stack();

    }

   

   public void push(int x) {

       if (stack.isEmpty()){

           stack.push(0L);

           min=x;

       }else{

           stack.push(x-min);

           if (x<min) min=x;

       }

    }

   

   public void pop() {

       if (stack.isEmpty()) return;

       

       long pop=stack.pop();

       

       if (pop<0)  min=min-pop;

    }

   

   public int top() {

       long top=stack.peek();

       if (top>0){

           return (int)(top+min);

       }else{

          return (int)(min);

        }

    }

   

   public int getMin() {

       return (int)min;

    }

}

0 0
原创粉丝点击