mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
40 lines
903 B
Rust
40 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
|
||
|
}
|
||
|
}
|