-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.rs
31 lines (28 loc) · 1.07 KB
/
Solution.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
use std::collections::VecDeque;
impl Solution {
#[allow(dead_code)]
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
// The deque contains the index of `nums`
let mut q: VecDeque<usize> = VecDeque::new();
let mut ans_vec: Vec<i32> = Vec::new();
for i in 0..nums.len() {
// Check the first element of queue, if it's out of bound
if !q.is_empty() && (i as i32) - k + 1 > (*q.front().unwrap() as i32) {
// Pop it out
q.pop_front();
}
// Pop back elements out until either the deque is empty
// Or the back element is greater than the current traversed element
while !q.is_empty() && nums[*q.back().unwrap()] <= nums[i] {
q.pop_back();
}
// Push the current index in queue
q.push_back(i);
// Check if the condition is satisfied
if i >= ((k - 1) as usize) {
ans_vec.push(nums[*q.front().unwrap()]);
}
}
ans_vec
}
}