Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration from the start of the array, find the maximum number inside the window at each moving.
Example
For array [1, 2, 7, 7, 8]
, moving window size k = 3
. return[7, 7, 8]
At first the window is at the start of the array like this
[|1, 2, 7| ,7, 8]
, return the maximum 7
;
then the window move one step forward.
[1, |2, 7 ,7|, 8]
, return the maximum 7
;
then the window move one step forward again.
[1, 2, |7, 7, 8|]
, return the maximum 8
;
Challenge
思路是这样的:
o(n) time and O(k) memory
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
// write your code here
vector<int> index;
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (i == 0) {
index.push_back(0);
} else {
int last_index = index.back();
while (nums[i] > nums[last_index]) {
int l = index.size() - 1;
index.erase(index.begin() + l);
if (index.size() == 0) {
break;
}
last_index = index.back();
}
index.push_back(i);
while (index[0] < i - k + 1) {
index.erase(index.begin());
}
}
if (i >= (k - 1)) {
res.push_back(nums[index[0]]);
}
}
return res;
}
};