summaryrefslogtreecommitdiff
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
commit2ee6240fb4b04e0f808e7cc6294baf596ef686ad (patch)
tree44f8e99d2ded91afce195618c0ace871bf987347
parent5ee9a2871769503099a5fab0a4ec70a109295d15 (diff)
downloadsolutions-2ee6240fb4b04e0f808e7cc6294baf596ef686ad.tar.gz
solutions-2ee6240fb4b04e0f808e7cc6294baf596ef686ad.tar.bz2
solutions-2ee6240fb4b04e0f808e7cc6294baf596ef686ad.zip
Add problem 155.
-rw-r--r--cpp/155-2.cpp48
-rw-r--r--cpp/155.cpp38
2 files changed, 86 insertions, 0 deletions
diff --git a/cpp/155-2.cpp b/cpp/155-2.cpp
new file mode 100644
index 0000000..aa07eee
--- /dev/null
+++ b/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/cpp/155.cpp b/cpp/155.cpp
new file mode 100644
index 0000000..48550be
--- /dev/null
+++ b/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_;
+};