- 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;
}
}
- 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默认的底层实现容器 (元素并不是严格的连续分布的)