LeetCode/rs/subarrays-with-k-different-integers.rs

40 lines
903 B
Rust
Raw Permalink Normal View History

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