代码随想录算法训练营第10天|二叉树的遍历(递归与迭代)

代码随想录算法训练营第10天|239. 滑动窗口最大值、347. 前K个高频元素

239. 滑动窗口最大值

题目链接

解答代码

class Solution {
    
    
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
    
    
        int n = nums.size();
        deque<int> q;
        for (int i = 0; i < k; ++i) {
    
    
            while (!q.empty() && nums[i] >= nums[q.back()]) {
    
    
                q.pop_back();
            }
            q.push_back(i);
        }

        vector<int> ans = {
    
    nums[q.front()]};
        for (int i = k; i < n; ++i) {
    
    
            while (!q.empty() && nums[i] >= nums[q.back()]) {
    
    
                q.pop_back();
            }
            q.push_back(i);
            while (q.front() <= i - k) {
    
    
                q.pop_front();
            }
            ans.push_back(nums[q.front()]);
        }
        return ans;
    }
};

347. 前K个高频元素

题目链接

解答代码

class Solution {
    
    
public:
    static bool cmp(pair<int, int>& m, pair<int, int>& n) {
    
    
        return m.second > n.second;
    }

    vector<int> topKFrequent(vector<int>& nums, int k) {
    
    
        unordered_map<int, int> occurrences;
        for (auto& v : nums) {
    
    
            occurrences[v]++;
        }

        // pair 的第一个元素代表数组的值,第二个元素代表了该值出现的次数
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> q(cmp);
        for (auto& [num, count] : occurrences) {
    
    
            if (q.size() == k) {
    
    
                if (q.top().second < count) {
    
    
                    q.pop();
                    q.emplace(num, count);
                }
            } else {
    
    
                q.emplace(num, count);
            }
        }
        vector<int> ret;
        while (!q.empty()) {
    
    
            ret.emplace_back(q.top().first);
            q.pop();
        }
        return ret;
    }
};

总结

                     日期: 2023 年 3 月 26 日
              学习时长: 1 h 0 m
                     难度: ★ \bigstar
累计完成题目数量: 32
距离目标还有数量: 268
                      小结:

  1. 没咋懂

猜你喜欢

转载自blog.csdn.net/qq_43212651/article/details/129785954