Description
Submission I
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int beg = 0, end = k - 1;
multiset<int> Set;
for(int i = beg; i <= end; ++i) {
Set.insert(nums[i]);
}
vector<int> rets;
rets.push_back(*Set.rbegin());
cout << *Set.rbegin();
while(end < nums.size()) {
Set.erase(Set.lower_bound(nums[beg++]));
end++;
if(end >= nums.size()) break;
Set.insert(nums[end]);
rets.push_back(*Set.rbegin());
}
return rets;
}
};
Submission II
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int n = nums.size();
vector<int> skipped(n, 0);
deque<int> dq;
vector<int> rets;
for(int i = 0; i < n; ++i) {
if(dq.empty() || nums[i] <= nums[dq.back()]) {
dq.push_back(i);
} else {
while(!dq.empty() && nums[dq.back()] <= nums[i]) {
dq.pop_back();
}
dq.push_back(i);
}
if(i + 1 >= k) {
rets.push_back(nums[dq.front()]);
}
if(i - dq.front() >= k-1) {
dq.pop_front();
}
}
return rets;
}
};
// 3 -1
References
- https://www.youtube.com/watch?v=b1rqOQ5p6EA
Submission III 210703
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq; // index
vector<int> rets;
for(int i = 0; i < nums.size(); ++i) {
while(!dq.empty() && i - dq.front() >= k) dq.pop_front();
while(!dq.empty() && nums[dq.back()] < nums[i]) dq.pop_back();
dq.push_back(i);
if(i >= k - 1)
rets.push_back(nums[dq.front()]);
}
return rets;
}
};
// [1 3 -1] -> [3, -1]