Actually, you don’t need to use unordered_map to implement lazy deletion. If you store both the value and the index in the max heap, you can achieve lazy deletion.
using std::vector; using std::priority_queue; using std::pair;
classSolution { public: vector<int> maxSlidingWindow(vector<int> &nums, int k) { int i, n = nums.size(); priority_queue<pair<int, int> > q;
for (i = 0; i < k; ++i) q.emplace(nums[i], i);
vector<int> ans = { q.top().first };
for (i = k; i < n; ++i) { q.emplace(nums[i], i);
while (q.top().second <= i - k) // Don't delete immediately; you can determine if it's inside based on its index. q.pop();
ans.push_back(q.top().first); } return ans; } };
Complexity O(n log n)
The recommended method is monotonic queue: using a monotonic decreasing deque.
deque<int> qIt stores the indices of the array, not the actual values.
This queue maintains a property: the values corresponding to the indices in the queue are monotonically decreasing. That is,nums[q[0]] >= nums[q[1]] >= ...。
classSolution { 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();
using std::vector; using std::priority_queue; using std::pair;
intmain() { int i, n, k; priority_queue<pair<int, int>, vector<pair<int, int> >, std::less<pair<int, int> > > max_heap;
scanf("%d %d", &n, &k);
vector<int> vec(n);
for (i = 0; i < n; i++) scanf("%d", &vec[i]);
for (i = 0; i < k; i++) max_heap.push({ vec[i], i });
printf("%d ", max_heap.top().first);
for (; i < n; i++) { while (!max_heap.empty() && i - max_heap.top().second >= k) // Note that max_heap.empty() otherwise it will cause an infinite loop. max_heap.pop();