From ec5319c3fb4e0b29086bea8ea55effee90d42ea0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 30 Mar 2024 23:58:56 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB992.=20Subarrays=20with=20K?= =?UTF-8?q?=20Different=20Integers=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/subarrays-with-k-different-integers.rs | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 rs/subarrays-with-k-different-integers.rs diff --git a/rs/subarrays-with-k-different-integers.rs b/rs/subarrays-with-k-different-integers.rs new file mode 100644 index 0000000..08b56f3 --- /dev/null +++ b/rs/subarrays-with-k-different-integers.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn subarrays_with_k_distinct(nums: Vec, mut k: i32) -> i32 { + let mut freqs = vec![0; nums.len() + 1]; + + let mut count = 0; + let mut current_count = 0; + + let mut i = 0; + let mut j = 0; + while j < nums.len() { + freqs[nums[j] as usize] += 1; + if freqs[nums[j] as usize] == 1 { + k -= 1; + } + j += 1; + + if k < 0 { + freqs[nums[i] as usize] -= 1; + k += 1; + current_count = 0; + + i += 1; + } + + if k == 0 { + while freqs[nums[i] as usize] > 1 { + freqs[nums[left] as usize] -= 1; + current_count += 1; + + i += 1; + } + + count += current_count + 1; + } + } + + count + } +}