leetcode-155. Min Stack

来源:互联网 发布:英语单词软件下载 编辑:程序博客网 时间:2024/04/29 13:20

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.

思路:用两个stack,一个存数字,一个存对应深度时对应的最小值

class MinStack {    //思路,两个stack,一个存数据,一个存stack里有n个数据时候对应的最小值    stack<int> numStack;    stack<int> minStack;public:    void push(int x) {        numStack.push(x);        if(minStack.empty())        {            minStack.push(x);        }        else        {            if(minStack.top() < x)            {                minStack.push(minStack.top());            }            else            {                minStack.push(x);            }        }    }    void pop() {        numStack.pop();        minStack.pop();    }    int top() {        return numStack.top();    }    int getMin() {        return minStack.top();    }};
0 0
原创粉丝点击