Leetcode 239 Solution in Rust🦀️

·

1 min read

use std::collections::VecDeque;

impl Solution {
    pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
        if nums.is_empty() || k < 1 || nums.len() < k as usize {
            return vec![];
        }
        let mut qmax: VecDeque<usize> = VecDeque::new();
        let mut res = vec![0; nums.len() - k as usize + 1];
        let mut idx = 0;
        for R in 0..nums.len() {
            while !qmax.is_empty() && nums[*qmax.back().unwrap()] <= nums[R] {
                qmax.pop_back();
            }
            qmax.push_back(R);
            if *qmax.front().unwrap() == R - k as usize {
                qmax.pop_front();
            }
            if R as i32 >= k - 1 {
                res[idx] = nums[*qmax.front().unwrap()];
                idx += 1;
            }
        }
        res
    }
}