Created
October 3, 2018 00:44
-
-
Save yokolet/8f59f4f051300549b01b275a42270451 to your computer and use it in GitHub Desktop.
Min Stack
This file contains hidden or 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
| """ | |
| Description: | |
| Design a stack that supports push, pop, top, and retrieving the minimum element in | |
| constant time. | |
| - push(x) -- Push element x onto stack. | |
| - pop() -- Removes the element on top of the stack. | |
| - top() -- Get the top element. | |
| - getMin() -- Retrieve the minimum element in the stack. | |
| Example: | |
| minStack = MinStack() | |
| minStack.push(-2) | |
| minStack.push(0) | |
| minStack.push(-3) | |
| minStack.getMin() # -3 | |
| minStack.pop() | |
| minStack.top() # 0 | |
| minStack.getMin() # -2 | |
| """ | |
| class MinStack: | |
| def __init__(self): | |
| """ | |
| initialize your data structure here. | |
| """ | |
| self.stack = [] | |
| self.mins = [] | |
| def push(self, x): | |
| """ | |
| :type x: int | |
| :rtype: void | |
| """ | |
| self.stack.append(x) | |
| if len(self.mins) == 0 or self.mins[-1] >= x: | |
| self.mins.append(x) | |
| def pop(self): | |
| """ | |
| :rtype: void | |
| """ | |
| tmp = self.stack.pop() | |
| if self.mins[-1] == tmp: | |
| self.mins.pop() | |
| return tmp | |
| def top(self): | |
| """ | |
| :rtype: int | |
| """ | |
| return self.stack[-1] | |
| def getMin(self): | |
| """ | |
| :rtype: int | |
| """ | |
| return self.mins[-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment