当前位置:网站首页>剑指Offer || :栈与队列(简单)
剑指Offer || :栈与队列(简单)
2022-06-27 02:11:00 【_索伦】
系列文章目录
- 【栈与队列】
前言
这个专栏记录leetcode刷题记录,以剑指Offer第2版为主
1. 用两个栈模拟队列
题目:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例:
输入:
[“CQueue”,“appendTail”,“deleteHead”,“deleteHead”]
[[],[3],[],[]]
输出:[null,null,3,-1]
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
代码
class CQueue {
private:
stack<int> s1;
stack<int> s2;
void push_In_S2() {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
public:
CQueue() {
}
// 入队列操作,入栈s1
void appendTail(int value) {
s1.push(value);
}
// 出栈操作
int deleteHead() {
if (s2.empty()) {
if (s1.empty()) {
return -1;
}
push_In_S2(); // 该函数负责把s1的元素入栈到s2
}
int value = s2.top();
s2.pop();
return value;
}
};
/** * Your CQueue object will be instantiated and called as such: * CQueue* obj = new CQueue(); * obj->appendTail(value); * int param_2 = obj->deleteHead(); */
2. 包含min函数的栈
题目:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
原题链接:包含min函数的栈
代码:
可借助辅助栈,每次入栈都记录最小值,让最小值保持在辅助栈的最上面。
class MinStack {
private:
stack<int> stk;
stack<int> min_stk;
public:
/** initialize your data structure here. */
MinStack() {
min_stk.push(INT_MAX);
}
void push(int x) {
stk.push(x);
min_stk.push(std::min(min_stk.top(), x));
}
void pop() {
stk.pop();
min_stk.pop();
}
int top() {
return stk.top();
}
int min() {
return min_stk.top();
}
};
边栏推荐
猜你喜欢

企业数字化转型:信息化与数字化

Hot discussion: what are you doing for a meaningless job with a monthly salary of 18000?

Flink learning 1: Introduction

为什么传递SPIF_SENDCHANGE标志SystemParametersInfo会挂起?
在 IDEA 里看个书很过分嘛!

Flink learning 5: how it works

H5 liquid animation JS special effect code

Arbre binaire OJ sujet

WiFi-IoT 鸿蒙开发套件样例开发

Look! In June, 2022, the programming language ranking list was released! The first place is awesome
随机推荐
svg拖拽装扮Kitty猫
Getting started with bluecms code auditing
C# Tcp服务器如何限制同一个IP的连接数量?
Microsoft365 developer request
Microsoft365开发人员申请
1、项目准备与新建
Google began to roll itself, AI architecture pathways was blessed, and 20billion generation models were launched
二叉树oj题目
Uninstallation of Dameng database
I earned 3W yuan a month from my sideline: the industry you despise really makes money!
Flink學習2:應用場景
Oracle/PLSQL: VSize Function
Memcached basics 13
企业数字化转型:信息化与数字化
Don't be brainwashed. This is the truth about the wages of 90% of Chinese people
在 IDEA 里看个书很过分嘛!
D's appendto packaging
Oracle/PLSQL: Rpad Function
How does the C # TCP server limit the number of connections to the same IP?
Press key to control LED status reversal