239. 滑动窗口最大值
加入时把小于val的全删除,删除时最多只删一个
class Solution {
private:
class MyQueue {
public:
void push(int value)
{
while (que.size() && que.back() < value)
{
que.pop_back();
}
que.push_back(value);
}
void pop(int value)
{
if (que.size() && que.front() == value)
{
que.pop_front();
}
}
int front()
{
return que.front();
}
private:
deque<int> que;
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue que;
for (int i = 0; i < k; i ++) que.push(nums[i]);
vector<int> res;
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 个高频元素
top k
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> umap;
for (int num : nums)
{
umap[num] ++;
}
priority_queue<pair<int, int>> pq;
for (auto [x, y] : umap)
{
pq.push({y, x});
}
vector<int> res;
while (k --)
{
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};