LeetCode 155: Min Stack

来源:互联网 发布:mac os 终端命令 编辑:程序博客网 时间:2024/06/15 09:41

题目链接:

https://leetcode.com/problems/min-stack/description/

描述

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 {public:    /** initialize your data structure here. */     long min;     stack<long> S;    MinStack() {    }    void push(long x) {        if(S.empty())        {           S.push(0L);            min = x;        }        else        {           S.push(x - min);            if(x < min)                min = x;        }    }    void pop() {       if(S.empty())           return;        else        {            long pop = S.top();            S.pop();            if(pop < 0)                min -= pop;        }    }    int top() {       long top = S.top();        if(top > 0)        {            return (top + min);        }        else        {            return (int)min;        }    }    int getMin() {        return (int)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(); */
原创粉丝点击