【剑指 offer】包含min函数的栈

题目描述:

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

思路:

用一个辅助栈,保存当前栈内的最小元素。每次入栈前判断当前的最小元素是原来的还是新进的。

代码:

class Solution {
public:
    void push(int value) {
        num.push(value);
        if (mins.empty())
            mins.push(value);
        else {
            int temp = mins.top();
            if (temp > value) temp = value;
            mins.push(temp);
        }
    }
    void pop() {
        num.pop();
        mins.pop();
    }
    int top() {
        return num.top();
    }
    int min() {
        return mins.top();
    }
private:
    stack<int> num;
    stack<int> mins;
};

好简洁的思路。。。我是个傻子。。。周末实验室很空。除了找不到饭友了,愉快。

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/89603719
今日推荐