My LeetCode grinding. Trying to do a problem a day.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. class MinStack:
  2. def __init__(self):
  3. self.stack = []
  4. self.minEl = None
  5. def push(self, x: int) -> None:
  6. node = Node(x)
  7. if self.minEl is None or node.value <= self.minEl.value:
  8. node.lastMin = self.minEl
  9. self.minEl = node
  10. self.stack.append(node)
  11. def pop(self) -> None:
  12. if len(self.stack) > 0:
  13. ret = self.stack[len(self.stack) - 1]
  14. if ret.value == self.minEl.value:
  15. self.minEl = self.minEl.lastMin
  16. self.stack = self.stack[0:len(self.stack) - 1]
  17. return ret.value
  18. return None
  19. def top(self) -> int:
  20. if len(self.stack) > 0:
  21. return self.stack[len(self.stack) - 1].value
  22. return None
  23. def getMin(self) -> int:
  24. return self.minEl.value
  25. def __str__(self):
  26. str_result = ""
  27. for x in self.stack:
  28. str_result += "\n"
  29. str_result += str(x)
  30. return str_result
  31. class Node:
  32. def __init__(self, x, lastMin = None):
  33. self.value = x
  34. self.lastMin = lastMin
  35. def __str__(self):
  36. return f"Value: {str(self.value)} Last Min: {str(self.lastMin)}"
  37. # Your MinStack object will be instantiated and called as such:
  38. values = []
  39. obj = MinStack()
  40. obj.push(-2)
  41. obj.push(0)
  42. obj.push(-3)
  43. values.append(obj.getMin())
  44. values.append(obj.pop())
  45. values.append(obj.top())
  46. values.append(obj.getMin())
  47. print("Expected: [-3, -3, 0, -2]")
  48. print("Got:", values)