[LeetCode] Sliding Window Maximum

239. Sliding Window Maximum

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
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++) {
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
class Solution {
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;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/sliding-window-maximum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.