Created
November 10, 2014 21:47
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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