Given an array A
of positive integers, call a (contiguous, not necessarily distinct) subarray of A
good if the number of different integers in that subarray is exactly K
.
(For example, [1,2,3,1,2]
has 3
different integers: 1
, 2
, and 3
.)
Return the number of good subarrays of A
.
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].
Note:
1 <= A.length <= 20000
1 <= A[i] <= A.length
1 <= K <= A.length
思路:一开始想直接sliding window求正好是K的情况的count,但是two pointer移动的时候会漏算掉(自己跑一个case就知道了),
from collections import defaultdict
class Solution(object):
def subarraysWithKDistinct(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
res=i=j=0
d=defaultdict(int)
while True:
while jK:
d[A[i]]-=1
if d[A[i]]==0: del d[A[i]]
i+=1
if len(d)==K: res+=1
if i>=len(A) or j>=len(A): break
while i
在two pointer移动的过程,其实可以计算不超过K的count(不会漏算),然后 正好K = 不超过K - 不超过K-1
from collections import defaultdict
class Solution(object):
def subarraysWithKDistinct(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
def count_at_most(K):
res=i=j=0
d=defaultdict(int)
while True:
while jK:
d[A[i]]-=1
if d[A[i]]==0: del d[A[i]]
i+=1
if len(d)<=K: res+=j-i
if j>=len(A): break
return res
return count_at_most(K)-count_at_most(K-1)