Add leetcode 155 task solution
This commit is contained in:
parent
956fe7e03e
commit
6043f03af3
1 changed files with 51 additions and 0 deletions
51
leetcode/stacks/0155_min_stack.py
Normal file
51
leetcode/stacks/0155_min_stack.py
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
# Link: https://leetcode.com/problems/min-stack/
|
||||||
|
from typing import List
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
class MinStack:
|
||||||
|
def __init__(self):
|
||||||
|
self._s: List[int] = []
|
||||||
|
self._min: List[int] = []
|
||||||
|
|
||||||
|
def push(self, val: int) -> None:
|
||||||
|
if len(self._s) == 0:
|
||||||
|
self._min.append(0)
|
||||||
|
elif val < self._s[self._min[-1]]:
|
||||||
|
self._min.append(len(self._s))
|
||||||
|
self._s.append(val)
|
||||||
|
|
||||||
|
def pop(self) -> None:
|
||||||
|
if len(self._s) - 1 == self._min[-1]:
|
||||||
|
self._min.pop()
|
||||||
|
self._s.pop()
|
||||||
|
|
||||||
|
def top(self) -> int:
|
||||||
|
return self._s[-1]
|
||||||
|
|
||||||
|
def getMin(self) -> int:
|
||||||
|
return self._s[self._min[-1]]
|
||||||
|
|
||||||
|
|
||||||
|
class TestSuite:
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def init_tests(self):
|
||||||
|
self.sol = MinStack()
|
||||||
|
|
||||||
|
def test_solution_1(self):
|
||||||
|
self.sol.push(1)
|
||||||
|
self.sol.push(-1)
|
||||||
|
self.sol.push(2)
|
||||||
|
self.sol.push(-2)
|
||||||
|
self.sol.pop()
|
||||||
|
assert self.sol.getMin() == -1
|
||||||
|
|
||||||
|
def test_solution_2(self):
|
||||||
|
breakpoint()
|
||||||
|
self.sol.push(-2)
|
||||||
|
self.sol.push(0)
|
||||||
|
self.sol.push(-1)
|
||||||
|
assert self.sol.getMin() == -2
|
||||||
|
assert self.sol.top() == -1
|
||||||
|
self.sol.pop()
|
||||||
|
assert self.sol.getMin() == -2
|
Loading…
Reference in a new issue