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

posted @ 2020-04-23 08:58  littledy  阅读(86)  评论(0编辑  收藏  举报