代码随想录day11 lc239, 347

  1. Sliding Window Maximum
    https://leetcode.cn/problems/sliding-window-maximum/
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int>dq;
        vector<int>res;
        for (int i = 0; i < nums.size(); i++) {
            while (!dq.empty() && dq.back() <= i - k) {
                cout << i << " " << dq.back() << endl;
                dq.pop_back();
            }
            while (!dq.empty() && nums[dq.front()] <= nums[i]) {
                dq.pop_front();
            }
            dq.push_front(i);
            if (i >= k - 1) {
                res.push_back(nums[dq.back()]);
            }
        }
        return res;
    }
}
  1. Top K Frequent Elements
    https://leetcode.cn/problems/top-k-frequent-elements/
    小顶推:每次将最小的弹出,留下最大的k个
class Solution {
public:
    typedef pair<int, int>p;
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int>res;
        unordered_map<int, int>mp;
        for (auto x: nums) {
            mp[x]++;
        }
        priority_queue<p, vector<p>, greater<p>>p;
        for (auto x: mp) {
            if (p.size() < k) {
                p.push({x.second, x.first});
            } else if (p.top().first < x.second) {
                p.pop();
                p.push({x.second, x.first});
            }
        }
        while (!p.empty()) {
            res.push_back(p.top().second);
            p.pop();
        }
        return res;
    }
};

priority queue自定义排序

typedef pair<int, int>p;
class myComparison {
    public:
    bool operator() (pair<int,int>&a, pair<int,int>&b) {
    	//小顶推,从小到大
        return a.second > b.second;
    }
};
priority_queue<p, vector<p>, myComparison>p;

栈是容器适配器,底层容器使用不同的容器,导致栈内数据在内存中是不是连续分布。
C++中deque是stack和queue默认的底层实现容器 (元素并不是严格的连续分布的)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值