-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path155.py
81 lines (68 loc) · 2.14 KB
/
155.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'''
155. Min Stack
https://leetcode.com/problems/min-stack/
Hi, here's your problem today.
This problem was recently asked by Uber:
Design a simple 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.
Note: be sure that pop() and top() handle being called
on an empty stack.
'''
from typing import *
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.values = []
self.minmum = []
def push(self, x: int) -> None:
self.values.append(x)
newMin = x
if self.minmum:
# set newMin then update
newMin = min(newMin, self.minmum[-1])
self.minmum.append(newMin)
def pop(self) -> None:
if self.values:
self.values.pop()
self.minmum.pop()
def top(self) -> int:
if self.values:
return self.values[-1]
return None
def getMin(self) -> int:
if self.minmum:
return self.minmum[-1]
return None
import unittest
class MinStackTest(unittest.TestCase):
def testExample(self):
minStack = MinStack()
minStack.push(-2)
minStack.push(0)
minStack.push(-3)
self.assertEqual(-3, minStack.getMin())
minStack.pop()
self.assertEqual(0, minStack.top())
self.assertEqual(-2, minStack.getMin())
def testEmptyCase(self):
minStack = MinStack()
minStack.pop()
self.assertEqual(None, minStack.top())
self.assertEqual(None, minStack.getMin())
def testEdgeCase(self):
minStack = MinStack()
minStack.push(1)
self.assertEqual(1, minStack.getMin())
self.assertEqual(1, minStack.top())
minStack.pop()
self.assertEqual(None, minStack.top())
self.assertEqual(None, minStack.getMin())
if __name__ == "__main__":
unittest.main()