Leetcode 155 Min Stack

来源:互联网 发布:无网络小游戏 编辑:程序博客网 时间:2024/06/18 04:18

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.

实现一个min stack

我写的比较基础 但是 time超了

public class MinStack {    private int count;     List<Integer> list;    /** initialize your data structure here. */    public MinStack() {       list  = new LinkedList<Integer>();       count = 0;    }        public void push(int x) {        count++;        list.add(x);    }        public void pop() {               list.remove(count-1);         count--;    }        public int top() {        return list.get(count-1);    }        public int getMin() {        int min = list.get(0);        for(int i = 0;i<count;i++){            if(list.get(i)<min){                min = list.get(i);            }        }        return min;    }}/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */

然后我发现其实是自己傻了 = =可以用stack来实现的啊========


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;//我觉得这里最聪明的地方在于减少了循环 在push的时候就检查比较最小值        }    }    public void pop() {        if (stack.isEmpty()) return;                long pop=stack.pop();                if (pop<0)  min=min-pop;//如果弹出去的是负数 说明压栈的时候 这个value小于当时的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
原创粉丝点击