add: 220316 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-16 12:40:32 +08:00
parent ac6c15a295
commit 8b0a1dcc49
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 41 additions and 1 deletions

40
cpp/2203/220316.cpp Normal file
View File

@ -0,0 +1,40 @@
#include <stack>
#include <vector>
#include <unordered_map>
#include <iostream>
class Solution {
public:
static bool validateStackSequences(const std::vector<int>& pushed, const std::vector<int>& popped) {
const int n = pushed.size();
std::unordered_map<int, int> m;
for (int i = 0; i < n; ++i)
m[pushed[i]] = i;
std::vector<int> processed(n);
for (int i = 0; i < n; ++i)
processed[i] = m[popped[i]];
int currentPushed = -1;
std::stack<int> s;
for (int i = 0; i < n; ++i) {
if (processed[i] > currentPushed) {
// == Push to current, and pop current immediately
for (++currentPushed; currentPushed < processed[i]; ++currentPushed) {
s.push(currentPushed);
}
} else {
if (s.empty() || s.top() != processed[i])
return false;
s.pop();
}
}
return true;
}
};
int main() {
std::cout << Solution::validateStackSequences({1,2,3,4,5}, {1,2,3,4,5});
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220315.cpp)
ADD_EXECUTABLE(2203 220316.cpp)