155. Min Stack

来源:互联网 发布:绿叶软件怎么样 编辑:程序博客网 时间:2024/06/07 17:19

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.

Example:

MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin();   --> Returns -3.minStack.pop();minStack.top();      --> Returns 0.minStack.getMin();   --> Returns -2.


用额外的变量记录最小值以及最小值在栈中的个数,剩下的交给treemap,最小值弹光以后从treemap取firstkey

class MinStack{int min=Integer.MAX_VALUE;int mincount=0;Stack<Integer> stack;TreeMap<Integer, Integer> treemap;public MinStack(){stack=new Stack<>();treemap=new TreeMap<>();}public void push(int x){if(x<min){min=x;mincount=0;}if(x==min)mincount++;if(!treemap.containsKey(x))treemap.put(x, 1);else {treemap.put(x, treemap.get(x)+1);}stack.push(x);}public void pop(){int x=stack.pop();if(x==min)mincount--;if(mincount==0){treemap.remove(min);min=treemap.firstKey();mincount=treemap.get(min);}}public int top(){return stack.peek();}public int getMin(){return min;}}



----------------------------------------------------------------------------------------------

https://discuss.leetcode.com/topic/4953/share-my-java-solution-with-only-one-stack

The question is ask to construct One stack. So I am using one stack.

The idea is to store the gap between the min value and the current value;

The problem for my solution is the cast. I have no idea to avoid the cast. Since the possible gap between the current value and the min value could be Integer.MAX_VALUE-Integer.MIN_VALUE;

public class MinStack {    long min;    Stack<Long> stack;    public MinStack(){        stack=new Stack<>();    }        public void push(int x) {        if (stack.isEmpty()){            stack.push(0L);            min=x;        }else{            stack.push(x-min);//Could be negative if min value needs to change            if (x<min) min=x;        }    }    public void pop() {        if (stack.isEmpty()) return;                long pop=stack.pop();                if (pop<0)  min=min-pop;//If negative, increase the min value            }    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