整数の配列numsが与えられると、配列の左端から右端に移動するサイズkのスライディングウィンドウがあります。スライディングウィンドウにはk個の数字しか表示されません。スライディングウィンドウは、一度に1つの位置だけ右に移動します。
スライディングウィンドウの最大値を返します。
例1:
入力:nums = [1,3、-1、-3,5,3,6,7]、k = 3
出力:[3,3,5,5,6,7]
説明:
スライディングウィンドウの位置最大
----------------
[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
例2:
入力:nums = [1]、k = 1
出力:[1]
分析:
主なことはpriority_queueの使い方を学ぶことです。通常のキューと比較して、emplaceを使用すると、最上位の要素が最大値であることを確認できます。コードは次のとおりです。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int n = nums.size();
priority_queue<pair<int, int>> q;
// 前k个构造一下优先队列
for(int i = 0; i < k; i++){
q.emplace(nums[i], i);
// 大顶堆,这个top对应的就是前k个里面最大的,从大到小的一个队列
// cout << q.top().first << " " << q.top().second ;
}
// 构造一个数组专门装每次窗口的最大值
vector<int> resultMax;
resultMax.push_back(q.top().first);
for(int i = k; i < nums.size(); i++){
q.emplace(nums[i], i);
// 为的是,假如后面窗口中的最大值比前面窗口的最大值小,那么堆顶一直都是原来窗口的最大值,需要把这些值给及时的pop掉,同样也能减轻堆的大小,比如[1, -1] k = 1这类情况
while(q.top().second <= i - k){
q.pop();
}
resultMax.push_back(q.top().first);
}
return resultMax;
}
};