LeetCode 239. Sliding Window Maximum

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) {
priority_queue<pair<int, int>> q;
for (int i = 0; i < k; ++i)
q.emplace(nums[i], i);
vector<int> ans = {q.top().first};
for (int i = k; i < nums.size(); ++i) {
q.emplace(nums[i], i);
while (q.top().second <= i - k)
q.pop();
ans.push_back(q.top().first);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
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 < nums.size(); ++i) {
while (!q.empty() && nums[i] >= nums[q.back()])
q.pop_back();
q.push_back(i);
while (q.front() <= i - k)
q.pop_front();
ans.push_back(nums[q.front()]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
const int n = nums.size();
vector<int> prefixMax(n), suffixMax(n);
for (int i = 0; i < n; ++i)
if (i % k == 0) prefixMax[i] = nums[i];
else prefixMax[i] = max(prefixMax[i - 1], nums[i]);
suffixMax[n - 1] = nums[n - 1];
for (int i = n - 2; i >= 0; --i)
if ((i + 1) % k == 0) suffixMax[i] = nums[i];
else suffixMax[i] = max(suffixMax[i + 1], nums[i]);
vector<int> ans;
for (int i = 0; i <= n - k; ++i)
ans.push_back(max(suffixMax[i], prefixMax[i + k - 1]));
return ans;
}
};