当前位置:网站首页>946. 验证栈序列 ●● & 剑指 Offer 31. 栈的压入、弹出序列 ●●
946. 验证栈序列 ●● & 剑指 Offer 31. 栈的压入、弹出序列 ●●
2022-07-23 10:50:00 【chenyfan_】
946. 验证栈序列 ●● & 剑指 Offer 31. 栈的压入、弹出序列 ●●
描述
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
示例
输入: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出: true
解释: 我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
题解
1. 模拟
所有的元素一定是按顺序 push 进去的,重要的是怎么 pop 出来。
因为元素值不重复,所以可以将 pushed 队列中的每个数都 push 到一个栈中,同时检查这个数是不是 popped 序列中下一个要 pop 的值,如果是就把它 pop 出来。
最后,检查是不是所有元素都 pop 出来了,即栈是否为空。
- 时间复杂度:O(N),其中 N 是 pushed 序列和 popped 序列的长度。
- 空间复杂度:O(N)。


class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
int idx = 0;
for(int num : pushed){
st.push(num);
// 循环检查当前栈顶元素是否为即将要 pop 的元素值
while(!st.empty() && st.top() == popped[idx] && idx < pushed.size()){
st.pop();
++idx; // 要 pop 的值后移
}
}
return st.empty();
}
};
边栏推荐
- 什么是服务器托管及和虚拟主机的区别
- Subsequence --- edit distance
- JSD-2204-会话管理-过滤器-Day19
- 力扣-单调栈
- 深入理解CAS (自旋锁)
- Jsd-2204 session management filter day19
- What is the difference between server hosting and virtual host
- Matlab simulation of solving multi-objective optimal value based on PSO optimization
- postgresql没有nvl的解决办法,postgresql查询所有的表
- MySQL执行顺序
猜你喜欢

Kirin V10 source code compilation qtcreater4.0.3 record

7.13web safety operation

select......for update 语句的功能是什么? 会锁表还是锁行?

Can multithreading optimize program performance?

颜值爆表 Redis官方可视化工具来啦,针不戳

C语言经典例题-将输入的两位数转成英文

it 农民工的现状和历史

BGP federal experiment

Safety 7.18 operation

报错 | cannot read property ‘_normalized‘ of undefined
随机推荐
After vscode is updated, the shortcut keys related to tab cannot be used
Modify SSH command line[ [email protected] ]Color
如何实现多个传感器与西门子PLC之间485无线通讯?
开源四足机器人 附设计图及代码「建议收藏」
What is the difference between server hosting and virtual host
airserver在哪里下载?使用方法教程
Part II how to design an RBAC authority system
深入理解L1、L2正则化
工业物联网中的时序数据
第三篇 RBAC权限管理 数据库设计详解
Matlab simulation of solving multi-objective optimal value based on PSO optimization
xlswriter - excel导出
Vision and intelligent learning recent journal reading and related knowledge learning
Batch deletion with RPM -e --nodeps
Opnsense - multifunctional, highly reliable and easy-to-use firewall (II)
Camera 手电筒修改
MySQL execution order
Exploration and practice of Ali multimodal knowledge atlas
Safety 7.18 operation
bgp基本配置