Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
// Max Heap
vector<int> maxSlidingWindow(vector<int>& nums, int k) { // time: O(nlogk); space: O(n)
if (nums.empty() || k <= 0) return vector<int>();
vector<int> res;
priority_queue<pair<int, int> > pq;
for (int i = 0; i < nums.size(); ++i) {
while (!pq.empty() && pq.top().second <= i - k) pq.pop();
pq.push({nums[i], i});
if (i >= k - 1) res.push_back(pq.top().first);
}
return res;
}
// Double-end queue
vector<int> maxSlidingWindow(vector<int>& nums, int k) { // time: O(n); space: O(n)
if (nums.empty() || k <= 0) return vector<int>();
vector<int> res;
deque<int> dq; // stores index
for (int i = 0; i < nums.size(); ++i) {
if (!dq.empty() && dq.front() == i - k) dq.pop_front();
while (!dq.empty() && nums[dq.back()] < nums[i]) dq.pop_back();
dq.push_back(i);
if (i >= k - 1) res.push_back(nums[dq.front()]);
}
return res;
}