Last active
August 29, 2015 14:19
-
-
Save HDegano/bb6670abb9a021a5b4ab to your computer and use it in GitHub Desktop.
Stack with Min/Max operation constant time.
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
public class MinStack { | |
private Stack<int> _stack = new Stack<int>(); | |
private Stack<int> _min = new Stack<int>(); | |
public void Push(int x) { | |
_stack.Push(x); | |
if(_min.Count == 0) _min.Push(x); | |
else { | |
if(x <= _min.Peek()) | |
_min.Push(x); | |
} | |
} | |
public void Pop() { | |
if(_stack.Pop() == _min.Peek()) | |
_min.Pop(); | |
} | |
public int Top() { | |
return _stack.Peek(); | |
} | |
public int GetMin() { | |
return _min.Peek(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment