From 7abf8c3ccc6126bac082e1c0b722c5a1f0f79dce Mon Sep 17 00:00:00 2001 From: jackfiled Date: Thu, 16 Jan 2025 22:19:32 +0800 Subject: [PATCH] 20250116 finished. --- src/problem/mod.rs | 2 + ..._shortest_subarray_with_or_at_least_k_i.rs | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/problem/p3095_shortest_subarray_with_or_at_least_k_i.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6405e04..a26bbc7 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -434,3 +434,5 @@ mod p2270_number_of_ways_to_split_array; 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; diff --git a/src/problem/p3095_shortest_subarray_with_or_at_least_k_i.rs b/src/problem/p3095_shortest_subarray_with_or_at_least_k_i.rs new file mode 100644 index 0000000..09e64ac --- /dev/null +++ b/src/problem/p3095_shortest_subarray_with_or_at_least_k_i.rs @@ -0,0 +1,61 @@ +/** + * [3095] Shortest Subarray With OR at Least K I + */ +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_3095() { + 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)); + } +}