問題描述
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()