剑指offer-----20、含有min的栈

1、题目描述

        定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

2、分析

        之前leetcode做过,(https://blog.csdn.net/zl6481033/article/details/89568340)。

3、代码

class Solution {
public:
    void push(int value) {
            s1.push(value);
        if(s2.empty()||s2.top()>value){
            s2.push(value);
        }
    }
    void pop() {
        if(s2.top()==s1.top()) s2.pop();
        s1.pop();
    }
    int top() {
        return s1.top();
    }
    int min() {
        return s2.top();
    }
private:
    stack<int> s1;
    stack<int> s2; 
};

4、相关知识点

        栈的相关知识。

posted @ 2019-06-05 17:37  吾之求索  阅读(109)  评论(0)    收藏  举报