题解 | #最大体重的牛#
最大体重的牛
https://www.nowcoder.com/practice/0333d46aec0b4711baebfeb4725cb4de
- 题目考察的知识点 : 类的定义,栈的使用
- 题目解答方法的文字分析:
- 类中维护一个主栈来存储牛的信息,每个元素是一个元组(id, weight)
- 同时维护一个最大体重栈,存储主栈中从栈底到栈顶的当前最大体重
- push时,将元素推入主栈,并比较元素权值与最大权值栈的栈顶,更新最大权值栈
- pop时,主栈和最大权值栈都执行pop操作
- top时返回主栈栈顶元素的权值
- getMax直接返回最大权值栈的栈顶即可
- 本题解析所用的编程语言:Python
- 完整且正确的编程代码
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param op string字符串一维数组 # @param vals int整型二维数组 # @return int整型一维数组 # class Solution: class MaxCowStack: def __init__(self): self.main = [] self.maxWeight = [] def push(self, id, weight): self.main.append((id, weight)) if not self.maxWeight or weight >= self.maxWeight[-1]: self.maxWeight.append(weight) def pop(self): if self.main: item = self.main.pop() if item[1] == self.maxWeight[-1]: self.maxWeight.pop() def top(self): if self.main: return self.main[-1][1] def getMax(self): return self.maxWeight[-1] def max_weight_cow(self, op: List[str], vals: List[List[int]]) -> List[int]: # write code here ans = [0] * len(op) maxCowStack = self.MaxCowStack() for i in range(len(op)): if op[i] == "MaxCowStack": ans[i] = -1 elif op[i] == "push": maxCowStack.push(vals[i][0],vals[i][1]) ans[i] = -1 elif op[i] == "pop": maxCowStack.pop() ans[i] = -1 elif op[i] == "top": ans[i] = maxCowStack.top() elif op[i] == "getMax": ans[i] = maxCowStack.getMax() return ans
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路