Website Summary Files Commits Branches @commit @diff @stats
path: root / Practicum / pract06 / solutions
diff options
context:
space:
mode:
Commit7ecb0c4f2407bbfe8a1300c576f0d2e4b7ef463f (patch)
Author
 Stoycho Kyosev <68247567+stoychoX@users.noreply.github.com>
2024-11-12 17:27:08 +0200
Committer
 GitHub <noreply@github.com>
2024-11-12 17:27:08 +0200
Files353d7575af2fe658939be110348d401c11f74423 /Practicum/pract06/solutions
Data-structures-and-algorithms-7ecb0c4f2407bbfe8a1300c576f0d2e4b7ef463f.tar
Data-structures-and-algorithms-7ecb0c4f2407bbfe8a1300c576f0d2e4b7ef463f.tar.gz
Data-structures-and-algorithms-7ecb0c4f2407bbfe8a1300c576f0d2e4b7ef463f.zip
Parentb445b1b7522eb8862dffd027f391ee224e25b241 (diff)
Parent4928246bfb99672c7f874a7b66cc3ef8cb02a3b2 (diff)
Merge pull request #15 from Daniel-Ghenov/main
2 files changed, 81 insertions, 0 deletions
-rw-r--r--Practicum/pract06/solutions/Task 01.cpp33
-rw-r--r--Practicum/pract06/solutions/Task 02.cpp48
diff --git a/Practicum/pract06/solutions/Task 01.cpp b/Practicum/pract06/solutions/Task 01.cpp
new file mode 100644
index 0000000..9ddd5e8
--- /dev/null
+++ b/Practicum/pract06/solutions/Task 01.cpp
@@ -0,0 +1,33 @@
+#include <vector>
+#include <stack>
+
+class Solution
+{
+public:
+ std::vector<int> nextGreaterElements(std::vector<int> &nums)
+ {
+ std::stack<std::pair<int, int>> stack;
+ std::vector<int> ans(nums.size(), -1);
+ for (int i = 0; i < nums.size(); ++i)
+ {
+ while (!stack.empty() && stack.top().first < nums[i])
+ {
+ ans[stack.top().second] = nums[i];
+ stack.pop();
+ }
+
+ stack.emplace(nums[i], i);
+ }
+
+ for (int i = 0; i < nums.size(); ++i)
+ {
+ while (!stack.empty() && stack.top().first < nums[i])
+ {
+ ans[stack.top().second] = nums[i];
+ stack.pop();
+ }
+ }
+
+ return ans;
+ }
+};
diff --git a/Practicum/pract06/solutions/Task 02.cpp b/Practicum/pract06/solutions/Task 02.cpp
new file mode 100644
index 0000000..6009d36
--- /dev/null
+++ b/Practicum/pract06/solutions/Task 02.cpp
@@ -0,0 +1,48 @@
+#include <string>
+#include <stack>
+#include <vector>
+
+class Solution
+{
+public:
+ std::vector<int> asteroidCollision(std::vector<int> &asteroids)
+ {
+ std::stack<int> stack;
+
+ for (int i = 0; i < asteroids.size(); ++i)
+ {
+ if (asteroids[i] > 0 || (stack.size() && stack.top() < 0))
+ {
+ stack.push(asteroids[i]);
+ continue;
+ }
+
+ bool addNeg = true;
+ while (stack.size() && stack.top() > 0 && stack.top() + asteroids[i] <= 0)
+ {
+ if (stack.top() + asteroids[i] == 0)
+ {
+ stack.pop();
+ addNeg = false;
+ break;
+ }
+ stack.pop();
+ }
+
+ if (addNeg && (stack.empty() || stack.top() < 0))
+ {
+ stack.push(asteroids[i]);
+ }
+ }
+
+ int idx = stack.size();
+ std::vector<int> result(idx);
+ while (stack.size())
+ {
+ result[--idx] = stack.top();
+ stack.pop();
+ }
+
+ return result;
+ }
+}; \ No newline at end of file