设计一个普通的栈,还有一个存储着最小值的栈。
每次push和pop时拿当前元素和栈顶比较,相应出栈进栈即可。
/** * return a array which include all ans for op3 * @param op int整型二维数组 operator * @return int整型一维数组 */ function getMinStack( op ) { let stack = []; let minStack = []; let res = []; for (let opr of op) { const [opt, val] = opr; switch (opt) { case 1: stack.push(val); if (val <= minStack[minStack.length - 1] || minStack.length <= 0) minStack.push(val); break; case 2: let popVal = stack.pop(); if (popVal === minStack[minStack.length - 1]) minStack.pop(); break; case 3: let minVal = minStack[minStack.length - 1]; res.push(minVal) break; } } return res; } module.exports = { getMinStack : getMinStack };