代码随想录算法训练营第13天|150.239.347

55 阅读1分钟

150

第一思路

根据题目提示,遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<string> st;
        for ( int i = 0; i < tokens.size(); i++) {
            if ( tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") st.push(tokens[i]);
            else {
                if ( tokens[i] == "+") {
                    int a = stoi(st.top());
                    st.pop();
                    int b = stoi(st.top());
                    st.pop();
                    int c = a + b;
                    string c1 = to_string(c);
                    st.push(c1);

                }
                if ( tokens[i] == "-") {
                    int a = stoi(st.top());
                    st.pop();
                    int b = stoi(st.top());
                    st.pop();
                    int c = a - b;
                    string c1 = to_string(c);
                    st.push(c1);

                }
                if ( tokens[i] == "*") {
                    int a = stoi(st.top());
                    st.pop();
                    int b = stoi(st.top());
                    st.pop();
                    int c = a * b;
                    string c1 = to_string(c);
                    st.push(c1);

                }
                if ( tokens[i] == "/") {
                    int a = stoi(st.top());
                    st.pop();
                    int b = stoi(st.top());
                    st.pop();
                    int c = a / b;
                    string c1 = to_string(c);
                    st.push(c1);

                }
            }
        }
        return stoi(st.top());

    }
};

结果测试用例正确,提交后解答错误

总结

原书中例子提交后会整数溢出,将int改为long类型

239

第一思路

窗口移动

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> res;
        for ( int i = 0, j = k - 1; j <= nums.size() - 1; j++){
            int max = *max_element(nums.begin()+i,nums.begin()+ j + 1);
            res.push_back(max);


        }
        return res;

    }
};

结果示例正确,提交后解答错误

347

总结: 思路不难,对于适配器和容器的使用不够熟练.