Given an array nums, a sliding window of size k moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.
Returns the maximum value in the sliding window.
Advanced:
Can you solve this problem in linear time complexity?
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
The position of the sliding window | 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 |
prompt:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length
Solution:
Use a deque to save the maximum value in the sliding window of each round.
1. Core code:
//myQueue.cpp
class MonotonicQueue {
private:
deque<int> data;
public:
void push(int n) {
while (!data.empty() && data.back() < n) {
data.pop_back();
}
data.push_back(n);
}
int max() {
return data.front();
}
void pop(int n) {
if (!data.empty() && data.front() == n) {
data.pop_front();
}
}
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MonotonicQueue window;
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (i < k-1) {
window.push(nums[i]);
}
else {
window.push(nums[i]);
res.push_back(window.max());
window.pop(nums[i - k + 1]);
}
}
return res;
}
};
2. Test code:
//test.cpp
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
class MonotonicQueue {
private:
deque<int> data;
public:
void push(int n) {
while (!data.empty() && data.back() < n) {
data.pop_back();
}
data.push_back(n);
}
int max() {
return data.front();
}
void pop(int n) {
if (!data.empty() && data.front() == n) {
data.pop_front();
}
}
};
void printVec(vector<int>& nums){
for (int i = 0; i < nums.size(); i++) {
cout << nums[i];
if (i != nums.size() - 1) {
cout << ",";
}
}
cout << endl;
}
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MonotonicQueue window;
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (i < k-1) {
window.push(nums[i]);
}
else {
window.push(nums[i]);
res.push_back(window.max());
window.pop(nums[i - k + 1]);
}
}
return res;
}
};
int main() {
Solution sol;
vector<int> nums = {
1, 3, -1, -3, 5, 3, 6, 7 };
vector<int> res = sol.maxSlidingWindow(nums, 3);
printVec(res);
system("pause");
return 0;
}
3. Remarks:
Source: LeetCode Question Number: 239
Link: LeetCode Sliding Window No239