单调队列&哈希表

347. 前 K 个高频元素

方法:哈希表

class Solution {
public:
    vector topKFrequent(vector& nums, int k) {
        vector res;
        unordered_map vis;
        vis.clear();
        for (int i = 0; i < nums.size(); ++i) ++vis[nums[i]];

        sort(nums.begin(), nums.end(),[&](const int a, const int b) {
            int cnta = vis[a], cntb = vis[b];
            if (cnta == cntb) return a < b;
            return cnta > cntb;
        });
        res.push_back(nums[0]);
        --k;

        for (int i = 1; i < nums.size() && k; ++i) {
            if (nums[i] == nums[i-1]) continue;
            res.push_back(nums[i]);
            --k;
        }
        return res;
    }
};

$时间复杂度O(nlogn),空间复杂度O(k)

239. 滑动窗口最大值

方法:单调队列

class Solution {
    #define maxn 100010
public:
    vector maxSlidingWindow(vector& nums, int k) {
        vector res;
        int hh = 0, tt = -1;
        int q[maxn];

        for (int i = 0; i < nums.size(); ++i) {
            if (hh <= tt && i - k + 1 > q[hh]) ++hh; 
            while (hh <= tt && nums[q[tt]] <= nums[i]) --tt;
            q[++tt] = i;
            if (i + 1 >= k) res.push_back(nums[q[hh]]); 
        }
        return res;
    }
};

$时间复杂度O(n),空间复杂度O(k)

你可能感兴趣的:(c++,leetcode,数据结构,算法)