1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/rs/subarrays-with-k-different-integers.rs
2024-03-30 23:58:56 +01:00

39 lines
903 B
Rust

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
}
}