leetcode-946:验证栈序列

给定 pushedpopped 两个序列,每个序列中的 值都不重复 ,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false

示例 1:

复制代码
输入: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

示例 2:

复制代码
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

提示:

  • 1 <= pushed.length <= 1000

  • 0 <= pushed[i] <= 1000

  • pushed 的所有元素 互不相同

  • popped.length == pushed.length

  • poppedpushed 的一个排列

    bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
    int* arr = (int*)malloc(sizeof(int) * pushedSize);
    for(int i = 0; i < poppedSize; i++) arr[i] = 1;
    int ind = 0;
    for(int i = 0; i < poppedSize; i++){
    while(arr[ind] == 0 || popped[i] != pushed[ind]) {
    ind++;
    if(ind == poppedSize) return false;
    }
    arr[ind] = 0;
    while(ind > 0 && arr[ind] == 0) ind--;
    }
    return true;
    }

    bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
    int* sta = (int*)malloc(sizeof(int) * poppedSize);
    int top = -1, x = 0;
    for(int i = 0; i < poppedSize; i++){
    if(top == -1 || sta[top] != popped[i]){
    while(x < poppedSize && pushed[x] != popped[i]){
    sta[++top] = pushed[x++];
    }
    if(x == poppedSize) return false;
    sta[++top] = pushed[x++];
    }
    top--;
    }
    return true;
    }

    bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
    int* sta = (int*)malloc(sizeof(int) * poppedSize);
    int top = -1, x = 0;
    for (int i = 0; i < poppedSize; i++){
    while(top == -1 || sta[top] != popped[i]){
    if(x == poppedSize) return false;
    sta[++top] = pushed[x++];
    }
    top--;
    }
    return true;
    }

相关推荐
空空潍12 分钟前
hot100-滑动窗口最大值(day11)
数据结构·c++·算法·leetcode
iAkuya29 分钟前
(leetcode)力扣100 35 LRU 缓存(双向链表&哈希)
leetcode·链表·缓存
氷泠1 小时前
课程表系列(LeetCode 207 & 210 & 630 & 1462)
算法·leetcode·拓扑排序·反悔贪心·三色标记法
老鼠只爱大米1 小时前
LeetCode算法题详解 15:三数之和
算法·leetcode·双指针·三数之和·分治法·three sum
菜鸟233号2 小时前
力扣416 分割等和子串 java实现
java·数据结构·算法·leetcode
Swift社区2 小时前
LeetCode 469 凸多边形
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 1458. 两个子序列的最大点积 困难
leetcode
Dream it possible!2 小时前
LeetCode 面试经典 150_二分查找_搜索二维矩阵(112_74_C++_中等)
leetcode·面试·矩阵
求梦8202 小时前
【力扣hot100题】缺失的第一个正数(12)
数据结构·算法·leetcode
黎雁·泠崖2 小时前
二叉树实战进阶全攻略:从层序遍历到OJ题深度解析
c语言·数据结构·leetcode