946. Validate Stack Sequences

Problem:

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Note:

  1. 0 <= pushed.length == popped.length <= 1000
  2. 0 <= pushed[i], popped[i] < 1000
  3. pushed is a permutation of popped.
  4. pushed and popped have distinct values.

思路

建立一个栈stk用来保存数据,用变量pop_index用来保存popped数组中下一个需要pop的值,依次遍历pushed数组中的元素,然后与popped数组中下表为pop_index的元素进行比较,如果相等,则stk弹出栈顶元素,++pop_index,若stk非空,继续比较,直到两者不相等或者stk为空则继续压入pushed数组中的元素。遍历完pushed后,所有在压栈过程中弹出的数不需要考虑,剩下的就是按照stk栈顶元素与popped[pop_index]一次比较,如果两者不相等,则说明栈顶元素与弹出值不对应,return false,否则return true

Solution (C++):

bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    stack<int> stk;
    int n = pushed.size(), pop_index = 0;
    for (int i = 0; i < n; ++i) {
        stk.push(pushed[i]);
        while (!stk.empty() && stk.top() == popped[pop_index]) {
            stk.pop();
            ++pop_index;   
        }
    }
    for (int i = pop_index; i < n; ++i) {
        if (stk.top() != popped[i])  return false;
        else  stk.pop();
    }
    return true;
}

性能

Runtime: 8 ms  Memory Usage: 7 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12758437.html