Skip to content

Instantly share code, notes, and snippets.

@cengiz-io
Created November 10, 2014 21:47
Show Gist options
  • Save cengiz-io/31f83db4b7c47045d29f to your computer and use it in GitHub Desktop.
Save cengiz-io/31f83db4b7c47045d29f to your computer and use it in GitHub Desktop.
Stack implementation which returns MIN() value in O(1) time (LeetCode OJ)
#include <stack>
class MinStack {
public:
void push(int x) {
s.push(x);
if (m.empty() == true || m.top() >= x) {
m.push(x);
}
}
void pop() {
if (m.top() == s.top()) {
m.pop();
}
s.pop();
}
int top() {
return s.top();
}
int getMin() {
return m.top();
}
private:
std::stack<int> s;
std::stack<int> m;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment