题解 | #最大体重的牛#

最大体重的牛

https://www.nowcoder.com/practice/0333d46aec0b4711baebfeb4725cb4de


使用两个栈来实现:一个栈存储牛的体重,另一个栈存储当前栈中的最大体重。
当推入新元素时,同时更新最大体重栈。
当弹出元素时,同时更新最大体重栈。
在常数时间内获取最大权值的牛的体重时,直接从最大体重栈中获取顶部元素即可。。
package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param op string字符串一维数组 
 * @param vals int整型二维数组 
 * @return int整型一维数组
*/
type MaxCowStack struct{
    stack []int
    maxStack []int  
}
func Constructor()MaxCowStack{
    return MaxCowStack{}
}
func (c *MaxCowStack)Pop(){
 if c.stack[len(c.stack)-1]==c.maxStack[len(c.maxStack)-1]{
    c.maxStack=c.maxStack[:len(c.maxStack)-1]
 }
  c.stack=c.stack[:len(c.stack)-1]
}
func(c *MaxCowStack)Push(id int,weight int){
    c.stack=append(c.stack, weight)
    if len(c.maxStack)==0||weight>c.maxStack[len(c.maxStack)-1]{
        c.maxStack=append(c.maxStack, weight)
    }

}
func(c *MaxCowStack)GetMax()int{
      return c.maxStack[len(c.maxStack)-1]

}
func(c *MaxCowStack)Top()int{
  return c.stack[len(c.stack)-1]
}
func max_weight_cow( op []string ,  vals [][]int ) []int {
    // write code here
     res := []int{}
    maxCowStack := Constructor()
    for i, operation := range op {
        if operation == "push" {
            maxCowStack.Push(vals[i][0], vals[i][1])
            res = append(res, -1) // 占位符
        } else if operation == "pop" {
            maxCowStack.Pop()
            res = append(res, -1) // 占位符
        } else if operation == "top" {
            res = append(res, maxCowStack.Top())
        } else if operation == "getMax" {
            res = append(res, maxCowStack.GetMax())
        }else if operation == "MaxCowStack" {
             res = append(res, -1)
        }
    }
    return res
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务