剑指-面试题30 包含min函数的栈

本文介绍了一种利用辅助栈实现包含min函数的栈数据结构的方法,确保了min、push及pop操作的时间复杂度均为O(1)。通过C++与Python代码示例详细解析了这一高效数据结构的设计与实现。

包含min函数的栈

题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)O(1)O(1)

思路:

按照剑指的思路,借助一个辅助栈实现min。
在这里插入图片描述


总结:
注意用C++和python实现基础栈的写法。

C++

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> min_stack;
    stack<int> help_stack;
    MinStack() {
    }
    
    void push(int x) {
        min_stack.push(x);
        if(help_stack.size()==0)
            help_stack.push(x);
        else
        {
            if(x < help_stack.top())
                help_stack.push(x);
            else
                help_stack.push(help_stack.top());
        }
    }
    
    void pop() {
        if (min_stack.size()==0)
            return ;
        min_stack.pop();
        help_stack.pop();
    }
    
    int top() {
        return min_stack.top();
    }
    
    int min() {
        return help_stack.top();
    }
};

/**
 * 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->min();
 */

python

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.help_stack = []


    def push(self, x: int) -> None:
        self.stack.append(x)
        if len(self.help_stack)==0:
            self.help_stack.append(x)
        else:
            if x < self.help_stack[-1]:
                self.help_stack.append(x)
            else:
                self.help_stack.append(self.help_stack[-1])


    def pop(self) -> None:
        if len(self.stack)==0:
            return 
        self.stack.pop()
        self.help_stack.pop()

    def top(self) -> int:
        return self.stack[-1]

    def min(self) -> int:
        return self.help_stack[-1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值