rs: add «992. Subarrays with K Different Integers»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-03-30 23:58:56 +01:00
parent 87750598a3
commit ec5319c3fb
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,39 @@
impl Solution {
pub fn subarrays_with_k_distinct(nums: Vec<i32>, 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
}
}