mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
rs: add «992. Subarrays with K Different Integers»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
87750598a3
commit
ec5319c3fb
1 changed files with 39 additions and 0 deletions
39
rs/subarrays-with-k-different-integers.rs
Normal file
39
rs/subarrays-with-k-different-integers.rs
Normal 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
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue