python 最小栈

python实现【栈的最小值】力扣题 题目:栈的最小值 具体描述: 请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。 示例: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minSta... 阅读详情

| 最小栈

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
 
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

| 题解

在这里插入图片描述

class MinStack:
    """
    题目要求在常数时间内获得栈中的最小值,因此不能在 getMin() 的时候再去计算最小值,最好应该在 push 或者 pop 的时候就已经计算好了当前栈中的最小值。
可以用一个栈,这个栈同时保存的是每个数字 x 进栈的时候的值 与 插入该值后的栈内最小值。即每次新元素 x 入栈的时候保存一个元组:(当前值 x,栈内最小值)。
这个元组是一个整体,同时进栈和出栈。即栈顶同时有值和栈内最小值,top()函数是获取栈顶的当前值,即栈顶元组的第一个值; getMin() 函数是获取栈内最小值,即栈顶元组的第二个值;pop() 函数时删除栈顶的元组。
每次新元素入栈时,要求新的栈内最小值:比较当前新插入元素 x 和 当前栈内最小值(即栈顶元组的第二个值)的大小。
新元素入栈:当栈为空,保存元组 (x, x);当栈不空,保存元组 (x, min(此前栈内最小值, x)))
出栈:删除栈顶的元组。
    """

    def __init__(self):
        self.stack = []

    def push(self, val: int) -> None:
        if not self.stack:
            self.stack.append((val, val))
        else:
            self.stack.append((val, min(val, self.stack[-1][-1])))

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

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

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

# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
python实现时间o(1)的最小栈的实例代码 这是毕业校招二面时遇到的手写编程题,当时刚刚开始学习python,整个栈写下来也是费了不少时间。毕竟语言只是工具,只要想清楚实现,使用任何语言都能快速的写出来。 何为最小栈?栈最基础的操作是压栈(push)和退栈(pop),现在需要增加一个返回栈内最小值的函数(get_min),要求get_min函数的时间复杂度为o(1)。python的栈肯定是使用list实现,只要将list的append和pop封装到stack类中,即实现了压栈和退栈。如果不考虑时间复杂度,我们第一反应一定是min(),min()可以在不开辟新空间的情况下o(n)的返回栈内最小值。但是如果栈内元素很多,并且get_min方 立即下载

相关推荐

从SIGGRAPH审稿人视角看:什么样的TOG论文更容易被接收?

本文从SIGGRAPH审稿人视角深入解析TOG论文的审稿标准与投稿策略,揭示如何提升论文接收概率。重点探讨创新性、技术深度、实验验证等核心评分维度,并提供写作技巧与审稿意见应对策略,帮助研究者优化ACM Transactions on Graphics投稿质量。

weixin_33721344的博客 108

Leetcode|155. 最小栈【笔记】

234. 回文链表【笔记】链接前言题目关键思路1相关知识疑问参考 链接 https://leetcode-cn.com/problems/min-stack/ 前言 把问题想太难了,一时难以下手 题目 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) —— 将元素 x 推入栈中。 pop() —— 删除栈顶的元素。 top() —— 获取栈顶元素。 getMin() —— 检索栈中的最小元素。 示例 输入: ["MinStack"

Kobaayyy的博客 427

STorM BGC V1.31硬件+SimpleBGC固件:从零搭建三轴云台开发环境(Keil+JLink避坑指南)

本文详细介绍了如何从零搭建STorM BGC V1.31硬件+SimpleBGC固件的三轴云台开发环境,涵盖硬件连接、Keil+JLink开发工具配置、固件编译与烧录等关键步骤,并提供了常见问题的解决方案和调试技巧,帮助开发者快速上手三轴云台开发。

weixin_28693683的博客 380

LeetCode - 155. 最小栈(python)

155. 最小栈 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) —— 将元素 x 推入栈中。 pop() —— 删除栈顶的元素。 top() —— 获取栈顶元素。 getMin() —— 检索栈中的最小元素。 示例: 输入: [“MinStack”,“push”,“push”,“push”,“getMin”,“pop”,“top”,“getMin”] [[],[-2],[0],[-3],[],[],[],[]] 输出: [null,null,null

qq_34770787的博客 347

固定翼飞行器建模(二)——MATLAB/Simulink建模、配平及线性化

MATLAB/Simulink固定翼建模、配平及线性化。

2302_80148937的博客 1万+

打开UG会安装报错:initialization internal ERROR 的提示框,提示line 1344 of错误的解决方案

打开UG会安装报错:initialization internal ERROR 的提示框,提示line 1344 of错误的解决方案

Q82556499的博客 3521

Python:实现最小栈

要想实现O(1)就得避免遍历,那就借助辅助栈,就是定义两个栈,其中一个是用来正常栈操作,另外一个存前面一个栈的最小值,设定最小值就是栈2的栈顶元素就行~或者设定一个结点类,用min()也是O(1)的,换汤不换药,辅助栈的太多人写了,我这里写用一个结点类,然后使用min的写法~,一般情况下直接求的话时间复杂度是O(n)的,不考虑时间复杂度旧如下所示就行(因为遍历了整个栈一遍)内检索到最小元素的栈,也就是。主要难的地方就是要实现。

weixin_55021541的博客 622

Hodgkin-Huxley Model

介绍了经典的动力学模型:HH Model

weixin_73557167的博客 2474

Python实现“最小栈“的两种方法

转载 Python实现"最小栈"的两种方法

qq_38603174的博客 405

rknn-toolkit推理yolov5-face.rknn模型--python代码

import os import urllib import traceback import time import sys import numpy as np import cv2 from rknn.api import RKNN ONNX_MODEL = 'yolov5s.onnx' RKNN_MODEL = 'yolov5s.rknn' IMG_PATH = './bus.jpg' DATASET = './dataset.txt' QUANTIZE_ON = True BOX_THR.

C/C++、嵌入式开发、深度学习算法、模型部署与推理优化 3079

YOLO26涨点改进 | 独家创新、损失函数改进篇 | TGRS 2025顶刊 | 带来AIoU小目标涨点损失函数,增强了目标检测中对边界框形状和尺寸的敏感度,适合复杂场景和小物体检测中有效涨点

AIoU损失函数通过自适应形状感知和尺寸敏感加权机制,有效解决了YOLO26原生损失函数在小目标检测中的缺陷。实验结果表明,AIoU损失函数在多个数据集上均取得了显著的性能提升,尤其在小目标检测和多任务场景下表现突出。自适应形状感知,对形状差异较大的目标给予更大惩罚,提高边界框拟合精度尺寸敏感加权,对小目标的宽高比例差异给予更大权重,增强模型对小目标特征的学习能力梯度连续性好,即使在IoU=0时仍能提供有效的梯度更新,解决小目标梯度消失问题。

qq_36130719的博客 159

Python-数据结构-栈-最小栈

Python-数据结构-栈-最小栈

qq_41188247的博客 508

34、实数域上高效负循环卷积算法解析

本文介绍了一种高效的实数域负循环卷积算法,通过引入离散傅里叶负循环变换(DFNT)避免传统方法的冗余,显著提升计算效率。文章详细分析了算法原理、误差传播机制,并推导出误差与方差界,提出无误差和基于3σ规则的参数设置方案。结合Cooley-Tukey与Gentleman-Sande FFT路径优化,实验验证了算法在不同精度和多项式长度下的性能优势与结果正确性,为密码学与信号处理等领域提供了高精度、高性能的卷积计算解决方案。

salt的博客 115

Python3实现最小栈

Python3实现最小栈 原题 https://leetcode-cn.com/problems/min-stack/ 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) – 将元素 x 推入栈中。 pop() – 删除栈顶的元素。 top() – 获取栈顶元素。 getMin() – 检索栈中的最小元素。 示例: MinStack minStack...

qq_18138105的博客 324

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

Python实现"最小栈

class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] # 存放所有元素 self.minStack = [] # 存放每一次压入数据时,栈中的最小值...

ganghaodream的博客 478

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

155.最小栈 Python实现

155.最小栈 Python实现 “Stay hungry ,Stay young" 最近刚刚回家,打了两天游戏,从今天开始坚持刷一点算法题来使自己保持思考的状态,并记录下整个过程。 题目简介详情参考LeetCode155题,这是一道简单题 题目要求是实现一个栈,能够实现pop和push操作,并能返回栈最顶端的元素,这些操作对于python的基本数据结构而言都非常简单,因此不再赘述,重点是题目要求实现一个getMin操作,在常数时间内找到栈中元素的最小值并返回。 这里,我简单梳理一下思路: 首先,栈的特

Lizzy的博客 413

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最小栈的实现(Python)

一、题目描述 实现一个栈,该栈带有出栈(pop)、入栈(push)、取最小元素(get_min)三个方法,要保证这三个方法的时间复杂度都是O(1)。 二、解题思路 可能大部分在看到这个题后,第一反应是创建一个整型变量min,用来存储栈中的最小元素,每新进来一个元素,就让它和最小元素比较,只要它比最小元素小,就更新它为最小元素。当调用get_min时,直接返回min的值即可。 以上算法错误之处在于只考虑了进栈的情况,当栈顶元素出栈时,此时栈中的最小值我们并不能知道是多少。 所以,只存一个最小值是不够的,我们需

weixin_43300894的博客 378

LeetCode:最小栈(Python版本)

LeetCode刷题日记最小栈思路Python代码 最小栈 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) – 将元素 x 推入栈中。 pop() – 删除栈顶的元素。 top() – 获取栈顶元素。 getMin() – 检索栈中的最小元素。 示例: MinStack minStack = new MinStack(); minStack...

Cassiel_Coder的博客. 717

栈 -(最小栈的实现)python描述

# -*- coding:utf-8 -*- """ Author: leadingme Mail:leadingme@qq.com MyWebsite:leadingme.top """ # 最小栈的实现 """ 算法要求: 设计一个支持push、pop、top操作并能在常数时间内检索到最小元素的栈 -> push(x): 将元素 x 推入栈中 ...

leadingme的博客 393

leetcode 最小栈 python3

class MinStack: def __init__(self): """ initialize your data structure here. """ self.minStack=[] def push(self, x: int) -> None: self.minStack.append(x) def pop(self) -> None: self.minSt

ywangjiyl的博客 132

python-leetcode 69.最小栈

2: 每次push时,将元素压入主栈,同时比较当前元素与辅助栈顶元素,将较小者压入辅助栈。设计一个支持push,pop,top,操作,并能在常数时间内检索到最小元素的栈。1:使用两个栈,一个主栈用于存储所有元素,另一个辅助栈用于存储当前元素的最小值。4:getmin,直接返回辅助栈最小的栈顶元素。3:每次pop时,同时从主栈和辅助栈弹出元素。

qq_51906990的博客 285

LeetCode 155. 最小栈 | Python

使用辅助栈,根据栈先入后出的性质,解决《155. 最小栈》问题

"大梦三千秋的博客 963

Python使用列表实现栈与队列,最小栈问题实现,用栈实现队列

先说Python语言的list的两个方法:list.append() list.pop() append()方法用于在列表末尾添加新的对象 。 list1 = ['Google','Runoob','Taobao'] list1.append('Baidu') print('更新后的列表:',list1) 更新后的列表: ['Google', 'Runoob', 'Taobao', 'Baidu'] pop()用于移除列表中的一个元素,默认为最后一个,并返回该元素值。 list1 = ["Google"

jq_98的博客 1418

leetcode-155.-最小栈(python)

最小栈 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x)-- 将元素 x 推入栈中。 pop()-- 删除栈顶的元素。 top()-- 获取栈顶元素。 getMin() -- 检索栈中的最小元素。 Python语言:使用辅助栈记录小的元素 class MinStack: def __in...

weixin_30727835的博客 177

最小栈(python实现)

题目描述: 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) – 将元素 x 推入栈中。 pop() – 删除栈顶的元素。 top() – 获取栈顶元素。 getMin() – 检索栈中的最小元素。 示例: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0)...

weixin_44512019的博客 324

力扣:(155)最小栈(Python)

设计一个支持pushpoptop操作,并能在常数时间内检索到最小元素的栈。实现MinStackMinStack()void pop()int top()

2503_91125378的博客 494
上一篇: python 有效的括号
下一篇: python 用一个数组实现三个栈
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一叶知秋的BLOG

创作不易 请多多关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值