题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
思路:
维护两个栈A,B,一个A用来存栈中所有元素,一个B是存栈中最小的元素。
push函数中,对于A来说,直接使用append方法添加到末尾,对于B需要判断栈中最后一个元素是否大于新元素,从而决定是否入栈B。
pop函数,先判断A,B两栈末尾是否相等,直接返回末尾元素即可。
top函数直接返回栈A 最后一个元素。
min函数直接返回栈B最后一个元素即为最小元素。
代码很简单,如下。
python
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if not self.min_stack or node <= self.min_stack[-1]:
self.min_stack.append(node)
def pop(self):
# write code here
if self.stack[-1] == self.min_stack[-1]:
self.min_stack.pop()
self.stack.pop()
def top(self):
# write code here
return self.stack[-1]
def min(self):
# write code here
return self.min_stack[-1]
c++
class Solution {
public:
void push(int value) {
stk.push(value);
if(stk_min.empty())
stk_min.push(value);
else if(value <= stk_min.top())
stk_min.push(value);
}
void pop() {
//stk.pop();
if(stk.top() == stk_min.top())
stk_min.pop();
stk.pop();
}
int top() {
return stk.top();
}
int min() {
return stk_min.top();
}
private:
stack<int> stk;
stack<int> stk_min;
};