The topics are as follows:
Give an array of integers that may contain duplicates, and a sliding window of size k, sliding the window from left to right in the array to find the maximum value within each window in the array. O (n) time, extra space for O (k)
Sample Example
to the array [1,2,7,7,8], the sliding window size is k = 3. returns [7,7,8].
Explain:
At the beginning, the status of the window is as follows:
[| 2, 7|, 7, 8] with a maximum value of 7;
Then the window moves to the right one:
[1, 7, 7|, 8], the maximum value is 7;
The last window then moves to the right one:
[1, 2, |7, 7, 8|], the maximum value is 8.
Problem Solving Ideas:
The complexity of O (n) obviously needs to be cached, and each window has a set portion, and the maximum value of the set portion is, of course, cached. As for the traversal, we can look like the following image (M1,m2,m3 is the maximum value of the window):
Since all we need is the maximum value in the cache, as long as the maximum value of the cache is guaranteed to be within the window's valid range, the maximum value is the maximum value of the window. Obviously, the sort cache is an unreliable method of extracting the maximum value, except for the complexity elevation problem, the array subscript stored in the cache is not matched with the sort, and the non-interval maximum in the cache may never be used, so we take the squeezing interval to extract the maximum value. With the advantage of two-way list, the last element is compared with the currently traversed elements, less than popback, until the list back element is greater than it, greater than the pushback, so that we can ensure that the list of any two elements within the interval of the elements are smaller than the two elements. As long as the first element of the list is within the interval, this element is the maximum value of the interval, and the next element is the maximum value.
The idea code is implemented as follows:
void Method (int *s,int len,int k)
{
deque<short>d;int i;
for (I=0;i<len;++i)
{
if (!d.empty () &&d.front () ==i-k)
D.pop_front ();
while (!d.empty () &&d.back () <s[i])
d.pop_back ();
D.push_back (i);
if (i>=k-1)
printf ("%d", S[d.front ()]);
}
}