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 thek numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7]
, and k = 3.
Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7]
.
#include <iostream> #include <vector> #include <queue> using namespace std; CORRECT // first, we can slove it using priority_queue. <strong>// time complexity: O(nklogk)</strong> vector<int> maxSlidingWindow(vector<int>& nums, int k) { int n = nums.size(); vector<int> res; k = k % n; priority_queue< int, vector<int>, less<int> > maxHeap; for(int i = 0; i <= n - k; ++i) { for(int j = i; j < i + k; ++j) { maxHeap.push(nums[j]); } res.push_back(maxHeap.top()); maxHeap = priority_queue <int>(); } return res; }
WRONG!! I was thinking to use a queue. but it failed on this test case :[1,3,1,2,0,5] ---> it should output: [3,3,2,5]. but the following code output: [3,3,1,5]
No Idea till now how to make it work.
// we can use a queue to always keep the current max number at the front. vector<int> maxSlidingWindowII(vector<int>& nums, int k) { queue<int> maxValues; vector<int> res; for(int i = 0; i < k; ++i) { if(maxValues.empty()) { maxValues.push(i); } else { while(!maxValues.empty()) { if(nums[i] > nums[maxValues.front()]) { maxValues.pop(); continue; } else break; } maxValues.push(i); } } res.push_back(nums[maxValues.front()]); for(int i = k; i < nums.size(); ++i) { if(maxValues.empty()) { maxValues.push(i); } else { while(!maxValues.empty() && ((i - maxValues.front()) >= k)) maxValues.pop(); while(!maxValues.empty()) { if(nums[i] > nums[maxValues.front()]) { maxValues.pop(); } else break; } maxValues.push(i); } res.push_back(nums[maxValues.front()]); } return res; }
CORRECT! using a fixed size queue and a deque.....
vector<int> maxSlidingWindowIII(vector<int>& nums, int k) { if(nums.size() == 0) return {}; queue<int> window; deque<int> maxes; vector<int> maxValue; for(int i = 0; i < nums.size(); ++i) { window.push(nums[i]); while(!maxes.empty() && (nums[i] > maxes.back())) { maxes.pop_back(); } maxes.push_back(nums[i]); if(window.size() == k) { maxValue.push_back(maxes.front()); int tmp = window.front(); window.pop(); if(tmp == maxes.front()) { maxes.pop_front(); } } } return maxValue; } int main(void) { vector<int> nums{1, 3, 1, 2, 0, 5}; vector<int> res = maxSlidingWindowIII(nums, 3); for(int i = 0; i < res.size(); ++i) { cout << res[i] << endl; } }