leetcode Min Stack

来源:互联网 发布:fs forse.js 编辑:程序博客网 时间:2024/05/21 10:11

原题链接: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:    void push(int x) {        if (val.empty() || x <= val.top()) val.push(x);        num.push(x);    }    void pop() {        if (num.top() <= val.top()) val.pop();        num.pop();    }    int top() {        return num.top();    }    int getMin() {        return val.top();    }private:    stack<int> num;    stack<int> val;};
0 0
原创粉丝点击