代码随想录第十天|150. 逆波兰表达式求值、239. 滑动窗口最大值、347.前 K 个高频元素

150. 逆波兰表达式求值

思路:遇到符号弹出上两个元素,注意要将string转成int。
题解:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> res;
        for (string ch : tokens)
        {
            if (ch == "+" || ch == "-" || ch == "*" || ch == "/")
            {
                int num2 = res.top();
                res.pop();
                int num1 = res.top();
                res.pop();
                if (ch == "+") res.push(num1 + num2);
                else if (ch == "-") res.push(num1 - num2);
                else if (ch == "*") res.push(num1 * num2);
                else res.push(num1 / num2);
            }
            else 
                res.push(stoi(ch));
        }
        return res.top();
    }
};

239. 滑动窗口最大值

思路:单调队列,队列内元素从小到大,只需要维护窗口中的最大值及右侧的部分元素,最大值左侧的元素无用。
题解:

class Solution {
private:
    class Myque
    {
        private:
        deque<int> que;
        public:
        void pop(int val)
        {
            if (!que.empty() && que.front() == val)
                que.pop_front();
        }
        void push(int val)
        {
            while (!que.empty() && val > que.back())
            {
                que.pop_back();
            }
            que.push_back(val);
        }
        int front()
        {
            return que.front();
        }
    };
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        Myque que;
        vector<int> res;
        for (int i = 0; i < k; ++i)
        {
            que.push(nums[i]);
        }   
        res.push_back(que.front());
        for (int i = k; i < nums.size(); ++i)
        {
            que.pop(nums[i-k]);
            que.push(nums[i]);
            res.push_back(que.front());
        }
        return res;
    }
};

347.前 K 个高频元素

思路:考察priority_queue,默认大顶堆。由于比较的是结构体优先级,我们需要自定义全局比较规则,构建出根据出现次数排序的小顶堆。
题解:

class Solution {
public:
    class cmp{
    public:
        bool operator()(const pair<int, int> &p1, const pair<int, int> &p2){
            return p1.second > p2.second;
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> map;
        for (int num : nums)
            ++map[num];
        priority_queue<pair<int, int>, vector<pair<int,int>>, cmp> q;
        for (auto it : map)
        {
            q.push(it);
            if (q.size() > k)
                q.pop();
        }
        vector<int> res;
        for (int i = 0; i < k; ++i)
        {
            res.push_back(q.top().first);
            q.pop();
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值