155. Min Stack
2021. 10. 23. 00:13ㆍLeetcode
Description:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
- MinStack() initializes the stack object.
- void push(int val) pushes the element val onto the stack.
- void pop() removes the element on the top of the stack.
- int top() gets the top element of the stack.
- int getMin() retrieves the minimum element in the stack.
'''
[1] self.min)
idea::
using self.min keep current min value.
but, when top value is current min, if pop, have to find new current_min. it takes O(n). n==len(stack)
so, it is not correct.
'''
'''
[2] using pairs)
idea::
when get_min() method is called, there is a top. and if not pop the top, below values are fixed. use this fact.
so, when push(val), push([val, min_val]), min_value would be current_min or new pushed value.
code::
(below)
- T/C: all method O(1)
- S/C: O(n). for stack, n==pushed values
'''
class MinStack:
def __init__(self):
self.stack=[]
def push(self, val: int) -> None:
cur_min=self.getMin()
if self.empty() or cur_min > val:
self.stack.append([val,val])
else:
self.stack.append([val,cur_min])
def pop(self) -> None:
if not self.empty():
self.stack.pop()
def top(self) -> int:
if not self.empty():
return self.stack[-1][0]
def getMin(self) -> int:
if not self.empty():
return self.stack[len(self.stack)-1][1]
return None
def empty(self) -> bool:
return len(self.stack)==0
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
'Leetcode' 카테고리의 다른 글
142. Linked List Cycle II (0) | 2021.10.23 |
---|---|
82. Remove Duplicates from Sorted List II (0) | 2021.10.23 |
25. Reverse Nodes in k-Group (0) | 2021.10.22 |
160. Intersection of Two Linked Lists (0) | 2021.10.22 |
49. Group Anagrams (0) | 2021.10.22 |