当前位置:网站首页>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();
}
};
边栏推荐
猜你喜欢
[email protected] ]Color"/>Modify SSH command line[ [email protected] ]Color

C语言经典例题-商品检验码

Kirin V10 source code compilation qtcreater4.0.3 record

uniapp路由跳转的六种方式

Part II how to design an RBAC authority system
![[pyGame actual combat] aircraft shooting masterpiece: fierce battle in the universe is imminent... This super classic shooting game should also be taken out and restarted~](/img/a3/087b1bc7445c53ddbd6d7334da51b9.png)
[pyGame actual combat] aircraft shooting masterpiece: fierce battle in the universe is imminent... This super classic shooting game should also be taken out and restarted~

上小学之前要学会的本领指引

Linux: analysis of the basic use of vim editor

安全作业7.22

C语言经典例题-逆序打印输入的两位数
随机推荐
Shell脚本案例---3
xlswriter - excel导出
力扣-单调栈
【Pygame实战】打扑克牌嘛?赢了输了?这款打牌游戏,竟让我废寝忘食。
MySQL执行顺序
C语言经典例题-将输入的两位数转成英文
STL map attribute
Completely uninstall MySQL in centos7
After vscode is updated, the shortcut keys related to tab cannot be used
在一个有序数组中查找具体的某个数字(二分查找or折半查找)
[pyGame practice] playing poker? Win or lose? This card game makes me forget to eat and sleep.
Vision and intelligent learning recent journal reading and related knowledge learning
深入理解L1、L2正则化
Exploration and practice of Ali multimodal knowledge atlas
Chapter 4 use%rest API classes create rest services
152. Product maximum subarray
Matlab simulation of solving multi-objective optimal value based on PSO optimization
Can multithreading optimize program performance?
Redis布隆过滤器
[hiflow] regularly send Tencent cloud SMS sending group