Subarrays with K Different Integers

Given an arrayAof positive integers, call a (contiguous, not necessarily distinct) subarray ofA_good_if the number of different integers in that subarray is exactlyK.

(For example,[1,2,3,1,2]has3different integers:1,2, and3.)

Return the number of good subarrays ofA.

Example 1:

Input: 
A = 
[1,2,1,2,3]
, K = 
2
Output: 
7
Explanation: 
Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:

Input: 
A = 
[1,2,1,3,4]
, K = 
3
Output: 
3
Explanation: 
Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

分析

1用atmost K做,f(exactly K) = f(atMost K) - f(atMost K-1).

2

count = distinct char.

while 让l,r之间始终都是distinct,同时用Pre++表示重复的数字,结果就是pre+1

count >K 时候左边缩一位(k-1),重置pre=0

Last updated

Was this helpful?