20-包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

var stack = []
function push(node)
{
    // write code here
    stack.push(node)
}
function pop()
{
    // write code here
    stack.pop()
}
function top()
{
    // write code here
    return stack[0]
}
function min()
{
    // write code here
    return Math.min.apply(this,stack)
}

增加了一个辅助栈,每次压入数据栈时,把当前栈里面最小的值压入辅助栈当中。这样辅助栈的栈顶数据一直是数据栈中最小的值。

比如,data中依次入栈, 5, 4, 3, 8, 10, 11, 12, 1
则min依次入栈, 5, 4, 3, 3, 3, 3, 3, 1

const stack = [],
minStack = [];
let tmp = null;
function push(node) {
   if (tmp !== null) {
       if (tmp > node) {
           tmp = node;
       }
       stack.push(node);
       minStack.push(tmp);
   } else {
       tmp = node;
       stack.push(node);
       minStack.push(tmp);
   }
}
function pop() {
   stack.pop();
   minStack.pop();
}
function top() {
   return stack[stack.length - 1];
}
function min() {
   return minStack[minStack.length - 1];
}
发布了83 篇原创文章 · 获赞 0 · 访问量 2003

猜你喜欢

转载自blog.csdn.net/weixin_43655631/article/details/104033763