From 402c045436c3453d4fd79bf8205786f9f659e2fb Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 17 Jan 2025 10:46:42 +0800 Subject: [PATCH] 20250117 finished. --- src/problem/mod.rs | 2 + ...shortest_subarray_with_or_at_least_k_ii.rs | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/problem/p3097_shortest_subarray_with_or_at_least_k_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index a26bbc7..6c51feb 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -436,3 +436,5 @@ mod p3065_minimum_operations_to_exceed_threshold_value_i; mod p3066_minimum_operations_to_exceed_threshold_value_ii; mod p3095_shortest_subarray_with_or_at_least_k_i; + +mod p3097_shortest_subarray_with_or_at_least_k_ii; diff --git a/src/problem/p3097_shortest_subarray_with_or_at_least_k_ii.rs b/src/problem/p3097_shortest_subarray_with_or_at_least_k_ii.rs new file mode 100644 index 0000000..2538d31 --- /dev/null +++ b/src/problem/p3097_shortest_subarray_with_or_at_least_k_ii.rs @@ -0,0 +1,61 @@ +/** + * [3097] Shortest Subarray With OR at Least K II + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn minimum_subarray_length(nums: Vec, k: i32) -> i32 { + let mut bits = [0; 31]; + let mut result = i32::MAX; + + let check = |b: &[i32; 31]| { + let mut real_k = 0; + + for (i, &v) in b.iter().enumerate() { + if v > 0 { + real_k |= 1 << i; + } + } + + real_k >= k + }; + + let mut left = 0; + for right in 0..nums.len() { + for i in 0..31 { + bits[i] += nums[right] >> i & 1; + } + + while left <= right && check(&bits) { + result = result.min((right - left + 1) as i32); + + for i in 0..31 { + bits[i] -= nums[left] >> i & 1; + } + left += 1; + } + } + + if result == i32::MAX { + -1 + } else { + result + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3097() { + assert_eq!(1, Solution::minimum_subarray_length(vec![1, 2, 3], 2)); + assert_eq!(3, Solution::minimum_subarray_length(vec![2, 1, 8], 10)); + assert_eq!(1, Solution::minimum_subarray_length(vec![1, 2], 0)); + } +}