剑指 Offer 31. 栈的压入、弹出序列
我写的笨比代码
使用标记加哈希,无论是时间复杂度还是空间复杂度都很差
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
int n = pushed.size(), cur = 0, pre = 0;
unordered_map<int, int> hash;
vector<int> flags(n+1);
for(int i = 0; i < n; i++){
hash[pushed[i]] = i;
}
for(int i = 0; i < n; i++){
cur = hash[popped[i]];
for(int k = cur + 1; k < n; k++){
if(flags[k] == 1) return false;
}
flags[cur] = 2;
if(cur > pre){
for(int j = 0; j < cur; j++){
if(flags[j] == 0){
flags[j] = 1;
}
}
}
pre = max(cur, pre);
}
return true;
}
};
直接使用模拟的方法来写
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
for (int i = 0, j = 0; i < popped.size(); i++) {
while ((st.empty() || st.top() != popped[i]) && j < pushed.size()) {
st.push(pushed[j++]);
}
if (popped[i] == st.top()) st.pop();
}
return st.empty();
}
};