LeetCode刷题之Min Stack

Problem

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.
My Solution

class MinStack {

    public int[] data;
    public int min = Integer.MAX_VALUE;
    public int top = -1;

    /** initialize your data structure here. */
    public MinStack() {
        data = new int[10000];
    }

    public void push(int x) {
        if (x < min) {
           min = x;
        }
        ++top;
        if (top < data.length - 1) {
            data[top] = x;
        }
    }

    public void pop() {
        if (top >= 0) {
            top--;
        }
        int t = top;
        min = Integer.MAX_VALUE;
        while (t != -1) {
            if (data[t] < min) {
               min = data[t];
            }
            t--;
        }
    }

    public int top() {
        if (top >= 0 && top <= data.length - 1) {
           return data[top];
        } else {
            return 0;
        }
    }

    public int getMin() {
       return min;
    }
}
Great Solution

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • 每一项运动项目都有其独特的内涵,由此迸发出与众不同的魅力。千里马再好,没有伯乐,难免孤芳自赏的黯然。关于足球,胖子...
    Lynn郑阅读 247评论 0 0
  • 小时候,跟着师傅在一片树林里倒腾跟头,刀枪棍棒使得欢,林间敞亮的很,夏虫鸣的厉害。 那时的树荫也凉快,光着膀子,风...
    朱才怪阅读 280评论 3 1
  • 抛硬币,问猫,算命,占卜,分析,思索,碎碎念……当一件事情这么牵扯一个人心的时候,人才能体悟那种潜在的绝望和孤独。...
    死不了放心吧我是你爷爷阅读 244评论 0 0