aboutsummaryrefslogtreecommitdiff
path: root/works/solutions/cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-05-13 16:12:01 +0800
committercrupest <crupest@outlook.com>2020-05-13 16:12:01 +0800
commite912950729b789c68d73b332db3003638371f215 (patch)
tree54e7e2c3e3397adfc7a0b5ec4f63cbc41ec06433 /works/solutions/cpp
parent7a25e555122e7f5ddbb225dde8f66fa312552eee (diff)
downloadcrupest-e912950729b789c68d73b332db3003638371f215.tar.gz
crupest-e912950729b789c68d73b332db3003638371f215.tar.bz2
crupest-e912950729b789c68d73b332db3003638371f215.zip
import(solutions): Add problem 155.
Diffstat (limited to 'works/solutions/cpp')
-rw-r--r--works/solutions/cpp/155-2.cpp48
-rw-r--r--works/solutions/cpp/155.cpp38
2 files changed, 86 insertions, 0 deletions
diff --git a/works/solutions/cpp/155-2.cpp b/works/solutions/cpp/155-2.cpp
new file mode 100644
index 0000000..aa07eee
--- /dev/null
+++ b/works/solutions/cpp/155-2.cpp
@@ -0,0 +1,48 @@
+#include <vector>
+#include <algorithm>
+
+class MinStack
+{
+public:
+ /** initialize your data structure here. */
+ MinStack()
+ {
+ // Although I really think this is just a trick for this problem.
+ // Leetcode does not give the input size. So I just make a reasonable assumption.
+ data_.reserve(10000);
+ min_stack_.reserve(10000);
+ }
+
+ void push(int x)
+ {
+ data_.push_back(x);
+ if (min_stack_.empty())
+ {
+ min_stack_.push_back(x);
+ }
+ else
+ {
+ min_stack_.push_back(std::min(min_stack_.back(), x));
+ }
+ }
+
+ void pop()
+ {
+ data_.pop_back();
+ min_stack_.pop_back();
+ }
+
+ int top()
+ {
+ return data_.back();
+ }
+
+ int getMin()
+ {
+ return min_stack_.back();
+ }
+
+private:
+ std::vector<int> data_;
+ std::vector<int> min_stack_;
+};
diff --git a/works/solutions/cpp/155.cpp b/works/solutions/cpp/155.cpp
new file mode 100644
index 0000000..48550be
--- /dev/null
+++ b/works/solutions/cpp/155.cpp
@@ -0,0 +1,38 @@
+#include <vector>
+#include <set>
+
+class MinStack
+{
+public:
+ /** initialize your data structure here. */
+ MinStack()
+ {
+ }
+
+ void push(int x)
+ {
+ data_.push_back(x);
+ sorted_data_.insert(x);
+ }
+
+ void pop()
+ {
+ const auto v = data_.back();
+ data_.pop_back();
+ sorted_data_.erase(sorted_data_.find(v));
+ }
+
+ int top()
+ {
+ return data_.back();
+ }
+
+ int getMin()
+ {
+ return *sorted_data_.cbegin();
+ }
+
+private:
+ std::vector<int> data_;
+ std::multiset<int> sorted_data_;
+};