スライディングウィンドウの最大値
タイトル
配列numsが与えられると、配列の左端から配列の右端に移動するサイズkのスライディングウィンドウがあります。スライディングウィンドウでのみk番号を表示できます。スライディングウィンドウは、一度に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
コードを実行する
class Solution {
public:
deque<int> dep;
void clean_queue(int idx,int i,vector<int>& nums){
if(!dep.empty()&&idx==dep.front())dep.pop_front();
while(!dep.empty()&&nums[dep.back()]<nums[i])dep.pop_back();
dep.push_back(i);
}
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
for(int i=0;i<k;i++){
clean_queue(i-k,i,nums);
}
res.push_back(nums[dep.front()]);
for(int i=k;i<nums.size();i++){
clean_queue(i-k,i,nums);
res.push_back(nums[dep.front()]);
}
return res;
}
};