946. 验证栈序列(力扣)

946. 验证栈序列
Problem: 946. 验证栈序列

思路

对栈的使用

解题方法

1.我们可以通过把pushed重新一个一个入我们自己创建的栈如果某次入栈碰到与poped第一个元素相同的那我们就对poped出栈处理(即跳过第一个元素);如此循环,直到我们的栈到最后被清空为止
image.png
当碰到与栈顶元素4相同时出栈
image.png
依次类推,当发现我么的栈为空是,则poped序列正确
image.png

复杂度

时间复杂度:

添加时间复杂度, 示例: O ( n ) O(n) O(n)

空间复杂度:

添加空间复杂度, 示例: O ( n ) O(n) O(n)

Code

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int[] stack = new int[popped.length+1];
        int top = 0;
        int count1 = 0;//为pushed的下标
        int count2 = 0;//poped的下标
        for(int i = 0;i<pushed.length*2;++i){//由于全部入栈出栈需要两个pushed数组的长度
            if(top>0){
                if(stack[top-1]==popped[count2]){
                    top--;
                    count2++;
                }else if(count1<pushed.length){//当pushed所有元素入栈完了就不需要入栈了
                    stack[top++] = pushed[count1++];
                }
            }else if(count1<=pushed.length) {
                stack[top++] = pushed[count1++];
            }
        }
        if(top == 0)return true;
        return false;
    }
}

相关推荐

  1. 每日OJ题_⑤_946. 验证序列

    2024-01-25 18:52:02       17 阅读
  2. [leetcode] 946. 验证序列

    2024-01-25 18:52:02       13 阅读
  3. :376. 摆动序列

    2024-01-25 18:52:02       29 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-25 18:52:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-25 18:52:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-25 18:52:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-25 18:52:02       18 阅读

热门阅读

  1. Flutter Image库详细介绍与使用指南

    2024-01-25 18:52:02       39 阅读
  2. 【ceph】ceph关于清洗数据scrub的参数分析

    2024-01-25 18:52:02       36 阅读
  3. ReactNative进阶(三十六):iPad横屏适配

    2024-01-25 18:52:02       38 阅读
  4. 力扣206-反转链表

    2024-01-25 18:52:02       35 阅读
  5. Linux系统文件权限详解

    2024-01-25 18:52:02       41 阅读
  6. [go] 桥接模式

    2024-01-25 18:52:02       41 阅读
  7. rust for循环步长-1,反向逆序遍历

    2024-01-25 18:52:02       37 阅读
  8. Spring-注解开发

    2024-01-25 18:52:02       38 阅读