栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【学习日志】2022.08.08 堆栈

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【学习日志】2022.08.08 堆栈

cpp

class MinStack {
    stack x_stack;
    stack min_stack;
public:
    
    MinStack() {
        min_stack.push(INT_MAX);
    }
    
    void push(int x) {
        x_stack.push(x);
        min_stack.push(::min(min_stack.top(),x));
    }
    
    void pop() {
        x_stack.pop();
        min_stack.pop();
    }
    
    int top() {
        return x_stack.top();
    }
    
    int min() {
        return min_stack.top();
    }   
};

python

class MinStack:
    def __init__(self):
        self.stack = []
        self.min_stack = [math.inf]

    def push(self, x: int) -> None:
        self.stack.append(x)
        self.min_stack.append(min(x, self.min_stack[-1]))

    def pop(self) -> None:
        self.stack.pop()
        self.min_stack.pop()

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

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

 2

cpp

class Solution {
public:
    bool validateStackSequences(vector& pushed, vector& popped) {
        stack st; // 建立辅助栈
        int index = 0;    
        for (int i = 0; i < pushed.size(); ++ i) { //依次遍历pushed中所有元素,模拟入栈操作
            st.push(pushed[i]);  
            //如果辅助栈的栈顶元素与popped中元素相等,模拟出栈操作
            while (!st.empty() && st.top() == popped[index]) {
                st.pop();
                index++;
            }
        }
        return st.empty(); //判断辅助栈的状态。为空,返回true;不为空,返回false。
    }
};

python

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        stack, i = [], 0
        for num in pushed:
            stack.append(num) # num 入栈
            while stack and stack[-1] == popped[i]: # 循环判断与出栈
                stack.pop()
                i += 1
        return not stack

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1037359.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号