问题描述
Design a 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.
设计一个栈,支持推,弹出,顶部,并在常数时间检索最小的元素。
push(x)——将元素x推入堆栈。
pop()——删除堆栈顶部的元素。
top()——获取top元素。
getMin()——检索堆栈中的最小元素。
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
python实现
基本思路是用一个链表来实现栈,每次添加删除节点只对链表头进行处理。同时,为了能在常数时间返回栈的最小值,在栈里维护一个最小值链表,每当出现小于或等于当前最小值的新节点时,将其加入到该链表头,以保证每次能在常数时间返回最小值。
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.val = None
self.next = None
self.min = ListNode(None)
def push(self, x):
"""
:type x: int
:rtype: None
"""
# Add new node and update the pointer of next.
tmp = ListNode(None)
tmp.val = self.val
tmp.next = self.next
self.val = x
self.next = tmp
# Update the list of min.
if self.min == None or self.min.val == None:
self.min = ListNode(x)
elif x <= self.min.val: # Add the new minimum to the head.
tmpMin = ListNode(None)
tmpMin.val = self.min.val
tmpMin.next = self.min.next
self.min.val = x
self.min.next = tmpMin
def pop(self):
"""
:rtype: None
"""
if self.val == self.min.val:
self.min = self.min.next
self.val = self.next.val
self.next = self.next.next
def top(self):
"""
:rtype: int
"""
return self.val
def getMin(self):
"""
:rtype: int
"""
return self.min.val
# 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()