题目考察的知识点
- 栈
题目解答方法的文字分析
- 略
本题解析所用的编程语言
- JavaScript
完整且正确的编程代码
function max_weight_cow( op , vals ) {
// write code here
let stack = [-1]
let res = []
for(let i= 1;i<op.length;i++){
if(op[i]=='push'){
res.push(vals[i][1])
stack.push(-1)
}else if(op[i]== 'pop'&&res.length>0){
res.pop()
stack.push(-1)
}else if(op[i]=='getMax'){
stack.push(Math.max(...res))
}else if(op[i]=='top'){
stack.push(res[res.length-1])
}
}
return stack
}、
这段代码定义了一个名为max_weight_cow
的函数,它接受两个参数op
和vals
。
函数内部使用了一个stack
数组和一个res
数组来模拟栈的行为。首先,将-1
压入stack
数组中作为初始值。
然后,函数使用一个循环来遍历op
数组。在每次迭代中,根据op[i]
的不同执行不同的操作:
- 如果
op[i]
等于push
,将vals[i][1]
压入res
数组,并向stack
数组中压入-1
。 - 如果
op[i]
等于pop
且res
数组的长度大于0,将res
数组的末尾元素弹出,并向stack
数组中压入-1
。 - 如果
op[i]
等于getMax
,将res
数组中的最大值(使用Math.max(...res)
)压入stack
数组。 - 如果
op[i]
等于top
,将res
数组中的最后一个元素压入stack
数组。
循环结束后,将stack
数组作为函数的返回值。
这段代码的功能是模拟一个栈,并支持push
、pop
、getMax
和top
操作。例如,通过传入['push', 'push', 'getMax', 'pop', 'top']
和[[], [5], [], [], []]
作为参数,可以得到[-1, -1, 5, -1, 5]
作为返回值。