|
| 1 | +/** |
| 2 | + * [239] Sliding Window Maximum |
| 3 | + * |
| 4 | + * Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. |
| 5 | + * |
| 6 | + * Example: |
| 7 | + * |
| 8 | + * |
| 9 | + * Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 |
| 10 | + * Output: [3,3,5,5,6,7] |
| 11 | + * Explanation: |
| 12 | + * |
| 13 | + * Window position Max |
| 14 | + * --------------- ----- |
| 15 | + * [1 3 -1] -3 5 3 6 7 3 |
| 16 | + * 1 [3 -1 -3] 5 3 6 7 3 |
| 17 | + * 1 3 [-1 -3 5] 3 6 7 5 |
| 18 | + * 1 3 -1 [-3 5 3] 6 7 5 |
| 19 | + * 1 3 -1 -3 [5 3 6] 7 6 |
| 20 | + * 1 3 -1 -3 5 [3 6 7] 7 |
| 21 | + * |
| 22 | + * |
| 23 | + * Note: <br /> |
| 24 | + * You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array. |
| 25 | + * |
| 26 | + * Follow up:<br /> |
| 27 | + * Could you solve it in linear time? |
| 28 | + */ |
| 29 | +pub struct Solution {} |
| 30 | + |
| 31 | +// submission codes start here |
| 32 | + |
| 33 | +use std::collections::VecDeque; |
| 34 | +impl Solution { |
| 35 | + pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> { |
| 36 | + let mut deq: VecDeque<(usize, i32)> = VecDeque::new(); |
| 37 | + let mut res = Vec::new(); |
| 38 | + for i in 0..nums.len() { |
| 39 | + // maintain sliding window |
| 40 | + if !deq.is_empty() && (*deq.front().unwrap()).0 as i32 <= (i as i32) - k { |
| 41 | + deq.pop_front(); |
| 42 | + let mut max = i32::min_value(); |
| 43 | + let mut count = 0_usize; |
| 44 | + for (j, &v) in deq.iter().enumerate() { |
| 45 | + if v.1 >= max { |
| 46 | + max = v.1; |
| 47 | + count = j; |
| 48 | + } |
| 49 | + } |
| 50 | + for _ in 0..count { |
| 51 | + deq.pop_front(); |
| 52 | + } |
| 53 | + } |
| 54 | + let num = nums[i]; |
| 55 | + if !deq.is_empty() && (*deq.front().unwrap()).1 <= num { |
| 56 | + while !deq.is_empty() { |
| 57 | + deq.pop_front(); |
| 58 | + } |
| 59 | + } |
| 60 | + deq.push_back((i, num)); |
| 61 | + if i + 1 >= k as usize { |
| 62 | + res.push((*deq.front().unwrap()).1); |
| 63 | + } |
| 64 | + } |
| 65 | + res |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// submission codes end |
| 70 | + |
| 71 | +#[cfg(test)] |
| 72 | +mod tests { |
| 73 | + use super::*; |
| 74 | + |
| 75 | + #[test] |
| 76 | + fn test_239() { |
| 77 | + assert_eq!(Solution::max_sliding_window(vec![9,10,9,-7,-4,-8,2,-6], 5), vec![10,10,9,2]); |
| 78 | + assert_eq!(Solution::max_sliding_window(vec![1,3,1,2,0,5], 3), vec![3,3,2,5]); |
| 79 | + assert_eq!(Solution::max_sliding_window(vec![7,2,4], 2), vec![7, 4]); |
| 80 | + assert_eq!(Solution::max_sliding_window(vec![1,-1], 1), vec![1, -1]); |
| 81 | + assert_eq!(Solution::max_sliding_window(vec![1,3,-1,-3,5,3,6,7], 3), vec![3,3,5,5,6,7]); |
| 82 | + } |
| 83 | +} |
0 commit comments