You are given an array of integers 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.
Time : O(n)
Space : O(k)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k){ deque<int> dq; vector<int> res; for(int i = 0; i < nums.size(); i++) { if(!dq.empty() and dq.front() == i - k) dq.pop_front(); while(!dq.empty() and nums[dq.back()] < nums[i]) dq.pop_back(); dq.push_back(i); if(i >= k - 1) res.push_back(nums[dq.front()]); } return res; } };
Time : O(n2logn)
Space : O(k)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k){ multiset<int> ms; vector<int> res; for(int i = 0; i < k - 1; i++) { ms.insert(nums[i]); } for(int i = k - 1; i < nums.size(); i++) { ms.insert(nums[i]); res.push_back(*ms.rbegin()); ms.erase(ms.find(nums[i-(k-1)])); } return res; } };