12. Min Stack / 155. Min Stack
- 本题难度: Medium/Easy
- Topic: Data Structure
Description
import heapq
import collections
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: 'int') -> 'None':
if len(self.stack) == 0:
self.stack.append((x,x))
return
if self.stack[-1][1]<x:
self.stack.append((x,self.stack[-1][1]))
else:
self.stack.append((x,x))
return
def pop(self) -> 'None':
return self.stack.pop()[0]
def top(self) -> 'int':
return self.stack[-1][0]
def getMin(self) -> 'int':
return self.stack[-1][1]
Your MinStack object will be instantiated and called as such:
obj = MinStack()
obj.push(x)
obj.pop()
param_3 = obj.top()
param_4 = obj.getMin()
我的代码
import heapq
import collections
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: 'int') -> 'None':
if len(self.stack) == 0:
self.stack.append((x,x))
return
if self.stack[-1][1]<x:
self.stack.append((x,self.stack[-1][1]))
else:
self.stack.append((x,x))
return
def pop(self) -> 'None':
return self.stack.pop()[0]
def top(self) -> 'int':
return self.stack[-1][0]
def getMin(self) -> 'int':
return self.stack[-1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
思路
参考了Leetcode Discussion代码。
getmin只需要get就好了,不需要弹出,所以并不需要heap来改变结构。
- 时间复杂度 O(n)

本文介绍了一种名为MinStack的数据结构设计与实现方法,该结构能在常数时间内获取栈中最小元素,同时支持push、pop、top等常规操作。通过使用元组存储每个元素及其当前最小值,避免了额外的空间开销。

829

被折叠的 条评论
为什么被折叠?



