题解 | #最大体重的牛#
最大体重的牛
https://www.nowcoder.com/practice/0333d46aec0b4711baebfeb4725cb4de
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param op string字符串vector
* @param vals int整型vector<vector<>>
* @return int整型vector
*/
void push(int id, int weight) {
stk.push(weight);
if (max_stk.size()) {
max_stk.push(max_stk.top() > weight ? max_stk.top():weight);
} else {
max_stk.push(weight);
}
}
int pop() {
if (stk.size()) {
int val = stk.top();
stk.pop();
max_stk.pop();
return val;
}
return -1;
}
int top() {
if (stk.size()) {
return stk.top();
}
return -1;
}
int getMax() {
return max_stk.top();
}
vector<int> max_weight_cow(vector<string>& op, vector<vector<int> >& vals) {
// write code here
vector<int> ans;
for (int i = 0; i < op.size(); i++) {
if (op[i] == "MaxCowStack") {
ans.push_back(-1);
}
if (op[i] == "push") {
push(vals[i][0], vals[i][1]);
ans.push_back(-1);
}
if (op[i] == "pop") {
pop();
ans.push_back(-1);
}
if (op[i] == "getMax") {
ans.push_back(getMax());
}
if (op[i] == "top") {
ans.push_back(top());
}
}
return ans;
}
private:
stack<int> stk;
stack<int> max_stk;
};

