0239.滑动窗口最大值
方法一:滑动窗口+双端队列
时间复杂度 $O(n)$,空间复杂度 $O(k)$。
impl Solution {
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
let mut ans = Vec::new();
let mut deque = std::collections::VecDeque::new();
for i in 0..nums.len() {
while !deque.is_empty() && nums[*deque.back().unwrap()] < nums[i] {
deque.pop_back();
}
deque.push_back(i);
if i >= (k - 1) as usize {
let elem = nums[*deque.front().unwrap()];
ans.push(elem);
if elem == nums[i + 1 - k as usize] {
deque.pop_front();
}
}
}
ans
}
}