包含 min 函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
时间限制:1秒 空间限制:32768K
代码
var stack = [];
var stackHelper = [];
function push(node)
{
// write code here
stack.push(node);
if (stackHelper[stackHelper.length - 1] > node || (stackHelper.length == 0)) {
stackHelper.push(node);
} else {
stackHelper.push(stackHelper[stackHelper.length - 1]);
}
}
function pop()
{
// write code here
if(stack.length > 0 && stackHelper.length > 0) {
stackHelper.pop();
return stack.pop();
} else {
return null;
}
}
function top()
{
// write code here
if (stack.length > 0) {
return stack[stack.length - 1];
} else {
return null;
}
}
function min()
{
// write code here
if(stackHelper.length > 0) {
return stackHelper[stackHelper.length - 1];
} else {
return null;
}
}
解题思路:
- 考虑到 push 和 pop 两个操作下,都不影响到现有最小值