包含min函数的栈
题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)O(1)O(1)。
思路:
按照剑指的思路,借助一个辅助栈实现min。

总结:
注意用C++和python实现基础栈的写法。
C++
class MinStack {
public:
/** initialize your data structure here. */
stack<int> min_stack;
stack<int> help_stack;
MinStack() {
}
void push(int x) {
min_stack.push(x);
if(help_stack.size()==0)
help_stack.push(x);
else
{
if(x < help_stack.top())
help_stack.push(x);
else
help_stack.push(help_stack.top());
}
}
void pop() {
if (min_stack.size()==0)
return ;
min_stack.pop();
help_stack.pop();
}
int top() {
return min_stack.top();
}
int min() {
return help_stack.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->min();
*/
python
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.help_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
if len(self.help_stack)==0:
self.help_stack.append(x)
else:
if x < self.help_stack[-1]:
self.help_stack.append(x)
else:
self.help_stack.append(self.help_stack[-1])
def pop(self) -> None:
if len(self.stack)==0:
return
self.stack.pop()
self.help_stack.pop()
def top(self) -> int:
return self.stack[-1]
def min(self) -> int:
return self.help_stack[-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.min()
本文介绍了一种利用辅助栈实现包含min函数的栈数据结构的方法,确保了min、push及pop操作的时间复杂度均为O(1)。通过C++与Python代码示例详细解析了这一高效数据结构的设计与实现。

466

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



