[leetcode 946] 验证栈序列

题目:https://leetcode.cn/problems/validate-stack-sequences/description/

[leetcode 946] 验证栈序列_第1张图片

非常经典的栈题目,考研中经常出现。思想就是模拟栈,下面是我第二次写这道题时的代码。时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n)

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> stk;
        int p = 0, q = 0;
        int len = pushed.size();
        while (q < len) {
            if (stk.empty()) {
                if (p < len) {
                    stk.push(pushed[p++]);
                }
            }
            else if (stk.top() == popped[q]) {
                stk.pop();
                q++;
            }
            else {
                if (p < len) {
                    stk.push(pushed[p++]);
                }
                else {
                    return false;
                }
            }
        }
        return stk.empty();
    }
};

能不能使用常数空间呢?可以,把 pushed 当作栈来处理。这是可以的,pushed中的数据不会冲突,因为栈会有pop,因此pushed作为栈的元素一定小于等于对应位置的数组元素!

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        int p = 0, q = 0, curr = 0;
        int len = pushed.size();
        while (q < len) {
            if (curr == 0) {
                if (p < len) {
                    pushed[curr++] = pushed[p++];
                }
            }
            else if (pushed[curr-1] == popped[q]) {
                curr--;
                q++;
            }
            else {
                if (p < len) {
                    pushed[curr++] = pushed[p++];
                }
                else {
                    return false;
                }
            }
        }
        return curr == 0;
    }
};

你可能感兴趣的:(leetcode,leetcode)