题解 | #最大体重的牛#

最大体重的牛

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;

};

全部评论

相关推荐

每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务