【栈-简单】面试题 03.04. 化栈为队

面试题 03.04. 化栈为队 对栈和队列基本操作的理解;对时间复杂度优化的思考;能否设计合理的辅助方法分离职责,比如函数;代码规范和模块化能力。这种思路在许多系统设计中也有类似应用,比如消息队列内部实现,因此非常值得深入理解。 阅读详情

【题目】
实现一个MyQueue类,该类用两个栈来实现一个队列。
【示例】
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
【说明】
你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
【代码】
【Python】
在这里插入图片描述

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.s1,self.s2=[],[]

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.s1.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        while self.s1:
            self.s2.append(self.s1.pop())
        rs=self.s2.pop()
        while self.s2:
            self.s1.append(self.s2.pop())
        return rs


    def peek(self) -> int:
        """
        Get the front element.
        """
        while self.s1:
            self.s2.append(self.s1.pop())
        
        rs=self.s2.pop()
        self.s1.append(rs)
        while self.s2:
            self.s1.append(self.s2.pop())
        return rs


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.s1)==0


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
Apollo 9.0 参考线生成器 -- ReferenceLineProvider 在基于参考线的规划算法中,参考线是Planning一切工作的基础和前提,所以搞清楚参考线怎么来的就变得很重要。为此,首先需要了解Planning 与 Routing的交互,通过交互得到路径片段,这些路径片段就告诉我们该怎么走,再在此基础上生成参考线,最后使用不同的平滑算法对参考线进行平滑,得到一条光滑的参考线。 阅读详情

相关推荐

Unity 游戏实例开发集合 之 Car Racing 2D (2D赛车) 休闲小游戏快速实现

Unity 游戏实例开发集合 之 Car Racing 2D (2D赛车) 休闲小游戏快速实现 目录 Unity 游戏实例开发集合 之 Car Racing 2D (2D赛车) 休闲小游戏快速实现 一、简单介绍 二、Car Racing 2D (2D赛车) 游戏内容与操作 三、相关说明 四、游戏代码框架 五、知识点 六、游戏效果预览 七、实现步骤 八、工程源码地址 九、延伸扩展 一、简单介绍 Unity 游戏实例开发集合,使用简单易懂的方式,讲解常见游戏的开发实现过程,方便

仙魁XAN 7702

LeetCode 【栈】面试题 03.04. 化栈为队 (简单)

算法小白开始刷题,本文包含了自己的思考过程,所以内容可能比较冗余,如需思路,可直接看文章后面的 优化解法。 题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci/ 题目 实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.po

Mr. Stone's Blog 411

PythonWeb开发框架—Django之工程创建和models的定义和增删改查

文章介绍了Django工程的创建、models的定义和增删改查

weixin_42476668的博客 990

【简单】面试题 03.04. 化栈为队

【题目】 实现一个MyQueue类,该类用两个栈来实现一个队列。 来源:leetcode 链接:https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci/ 【示例】 MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 【

... 142

定时器(PWM输出)触发ADC采样(DMA)——STM32CubeMX

已知 Tclk 为 84MHz , 我们需要 Tout 为 200ms 即 200000us , 不妨先让PSC为 839, 带入上述公式可得 ARR = 19999. 这样算出来之后ARR和PSC都在0~65535的范围, 则可以使用这组参数。例如,如果时钟频率为1MHz,并且PSC设置为1000,则实际的定时频率将为1kHz。当重装载值(Period 或 ARR)设置为 500 时,意味着定时器需要计数 500 个时钟周期才会触发中断。例如,如果时钟频率为1MHz,则Tclk为1微秒。

2301_77123899的博客 1万+

JOOQ用法和实例

jOOQ,是一个ORM框架,利用其生成的Java代码和流畅的API,可以快速构建有类型约束的安全的SQL语句。jOOQ的核心优势是可以将数据库表结构映射为Java类,包含表的基本描述和所有表字段。通过jOOQ提供的API,配合生成的Java代码,可以很方便的进行数据库操作生成的Java代码字段类型是根据数据库映射成的Java类型,在进行设置和查询操作时,因为是Java代码,都会有强类型校验,所以对于数据的输入,是天然安全的,极大的减少了SQL注入的风险。

m0_67403076的博客 1377

【Python】【难度:简单】Leetcode 面试题 03.04. 化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 说明: 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。 你所使..

thomashhs12的博客 325

串口调试神器诞生记:我是如何用Cursor+AI自动生成C#上位机的(含VSCode插件清单)

本文详细介绍了如何利用Cursor和AI技术快速开发C#上位机程序,实现高效的串口通讯调试。从开发环境搭建到代码自动生成,再到性能优化和功能增强,全面展示了AI辅助开发在串口调试中的实际应用和显著效率提升。

weixin_28340315的博客 300

面试题 03.04. 化栈为队(简单)

题目描述 实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 做题思路 同用两个栈实现队列(简单)_黑黑藏不住的博客-优快云博客 代码 class MyQueue { Stack<Int..

zxw20171828的博客 254

基于深度强化学习的柔性作业车间动态调度

在追求敏捷和灵活的生产调度方面,处理不可预测的动态事件的能力变得越来越重要。与此同时,生产系统中的网络-物理融合产生了大量需要实时挖掘和分析的工业数据。为了便于这种实时控制,本研究提出了一种分层分布式的体系结构来解决动态柔性作业车间调度问题。采用双深度Q网络算法(DDQN)训练调度智能体,捕捉生产信息与调度目标之间的关系,为具有恒定任务到达的柔性作业车间实时做出调度决策。为了处理动态调度中问题的可变规格说明,提出了专门的状态和动作表示法。此外,还提出了一种代理奖励整形技术(surrogate reward

太剧烈的快乐与太剧烈的悲哀是有相同之点的——同样地需要远离人群! 1万+

基于simulink的BMS系统中电池单体故障隔离与恢复建模

本文介绍了使用Simulink构建BMS电池单体故障诊断与容错控制模型的方法。主要内容包括:1)搭建12串锂电池组模型;2)实现单体故障注入(过压、断线等);3)设计故障诊断与隔离模块(采用Stateflow状态机);4)开发恢复判断逻辑(需满足电压、温度等条件);5)系统监控与仿真设置。文章还提供了工程实践建议,如防环流设计、通信冗余等,并指出进阶方向(多故障处理、AI预警等)。该模型适用于新能源汽车、储能系统的BMS设计,可提高系统可靠性和安全性。

xiaoheshang_123的博客 140

面试题 03.05. 化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。 class MyQueue { public: /** Initialize your data structure here. */ stack<int> st1; stack<int> st2; MyQueue() { } ...

yeyueyouhun的博客 246

SAR成像专栏目录

为方便大家阅读,我做了一个专栏目录,蓝色字有超链接,可以直接打开。 本专栏默认读者已具备雷达系统的基本知识或者已阅读过雷达导论专栏中的文章。 1. 概述 SAR成像概述 星载SAR的各项指标解读(史上最全) SAR成像算法的实现途径与算力分析 2. SAR成像原理与SAR系统简介 雷达与分辨率 SAR成像原理与方法 SAR图像的形成和处理 SAR系统设计 3. 点目标仿真 点目标仿真(一)—— 数学模型 点目标仿真(二)—— Matlab仿真 4. 成像算法 更新中 雷达导论专

7462

【LeetCode每日一题】——面试题03.04.化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。

IronmanJay 289

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

LeetCode:面试题 03.04. 化栈为队(栈)

面试题 03.04. 化栈为队 实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 说明: 你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作

stackempty2的博客 179

深度学习工具包 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")

leetcode 面试题03.04.化栈为队 Java

化栈为队题目链接描述示例代码 题目链接 https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci/ 描述 实现一个MyQueue类,该类用两个栈来实现一个队列。 说明: 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操

博主是个二次元死肥宅~ 237

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

【leetcode】面试题 03.04. 化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 说明: 你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。 你所使用的语言也许不

爱小七爱生活的博客 198

面试题 03.04 - 化栈为队

一 目录 不折腾的前端,和咸鱼有什么区别目录一 目录二 题目三 解题思路四 统计分析五 解题套路二 题目 实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQue...

weixin_41806099的博客 198

化栈为队(Java实现)

化栈为队 题目 面试题 03.04. 化栈为队 实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 分析 该题的思路和《用两个栈实现队列(Java实现)》一样。不过这里要注意一点,可以在pop()的时候,复用peek的逻辑。 代码

卜大爷的博客 2万+

力扣——【面试题 03.04. 化栈为队】

【代码】力扣——【面试题 03.04. 化栈为队】

2201_75478206的博客 236

leetcode:面试题 03.04. 化栈为队

题目来源 https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci/ 题目描述 题目解析 两个栈: 一个读栈rStack 一个写栈wStack 当push时 直接往wStack压入元素 当pop时:(一个空的队列不会调用 pop 或者 peek 操作) 如果rStack为空,将wStack的元素全部压入rStack, 然后rStack.pop第一个元素 如果rStack不为空,rStack.pop第一个元素 当peek时:

OceanStar的博客 331

leetcode —— 面试题 03.04. 化栈为队

实现一个MyQueue类,该类用两个栈来实现一个队列。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci 著作

fightfightfightf的博客 333

LeetCode-面试题 03.04:化栈为队

class MyQueue { private: stack<int> s1, s2; public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(i...

weixin_44587168的博客 272
上一篇: 【栈-简单】1047. 删除字符串中的所有相邻重复项
下一篇: 【栈-简单】682. 棒球比赛
菜菜2022
博客等级 码龄9年 67粉丝 1033原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值