The problem of the maximum value of sliding window in Likou 2021.1.2

Problem description:
Given an integer 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.

Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Sliding window Maximum position


[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
Example 2:
Input: nums = [1], k = 1
Output: [1]

Example 3:
Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:
Input: nums = [9,11], k = 2
Output: [11]

Example 5:
Input: nums = [4,-2], k = 2
Output: [4]

Idea:
For the "maximum", we can think of a very suitable data structure, that is, the priority queue (heap), where the large root heap can help us maintain the maximum value in a series of elements in real time.

For this problem, initially, we put the first k elements of the array nums into the priority queue. Whenever we move the window to the right, we can put a new element in the priority queue. At this time, the element at the top of the heap is the maximum value of all elements in the heap. However, this maximum value may not be in the sliding window. In this case, the position of this value in the array nums appears on the left side of the left boundary of the sliding window. Therefore, when we continue to move the window to the right, this value will never appear in the sliding window, and we can permanently remove it from the priority queue.

We continue to remove the element at the top of the heap until it actually appears in the sliding window. At this time, the top element of the heap is the maximum value in the sliding window. In order to facilitate the judgment of the positional relationship between the top element of the heap and the sliding window, we can store the two-tuple (num, index) in the priority queue, which means that the subscript of the element num in the array is index.

代码:
class Solution { public: vector maxSlidingWindow(vector& nums, int k) { int n = nums.size(); priority_queue<pair<int, int>> q; for (int i = 0; i < k; ++i) { q.emplace(nums[i], i); } vector ans = {q.top().first}; for (int i = k; i < n; ++i) { q.emplace(nums[i], i); while (q.top().second <= i - k) { q.pop(); } ans.push_back(q.top().first); } return ans; } };

















Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112113819