1.Description
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.
Example:
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.
Subscribe to see which companies asked this question.
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.
Example:
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.
Subscribe to see which companies asked this question.
解讀
題目中要常數時間內能夠解決該問題,所以應當考慮把最小值同時壓棧的操作
2.Solution
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
#這裏push數據的時候,把最小值也同時壓入,已tuple的方式壓入
min = self.getMin()
if min == None or x < min:
min = x
self.stack.append((x, min))
def pop(self):
"""
:rtype: void
"""
if self.stack == []:
return None
self.stack.pop()
def top(self):
"""
:rtype: int
"""
if self.stack == []:
return None
return self.stack[-1][0]
def getMin(self):
"""
:rtype: int
"""
if self.stack == []:
return None
return self.stack[-1][1]