题解 | #最大体重的牛#
最大体重的牛
https://www.nowcoder.com/practice/0333d46aec0b4711baebfeb4725cb4de
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param op string字符串一维数组
* @param vals int整型二维数组
* @return int整型一维数组
*/
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
}
module.exports = {
max_weight_cow : max_weight_cow
};
考点:栈
思路;根据题意,先定义2个数组,一个用来放结果,一个用来存储牛的体重。然后通过if判断需要进行的操作,根据不同的操作对前2个数组做出改变。最后输出结果数组即可。

