992. Subarrays with K Different Integers

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/86906740

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: 12, 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. 1 <= A.length <= 20000
  2. 1 <= A[i] <= A.length
  3. 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 j<len(A) and len(d)<=K:
                d[A[j]]+=1
                j+=1
                if len(d)==K: res+=1
            while i<len(A) and len(d)>K:
                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<len(A):
            d[A[i]]-=1
            if d[A[i]]==0: del d[A[i]]
            i+=1
            if len(d)==K: res+=1
        return res
    
s=Solution()
#print(s.subarraysWithKDistinct(A = [1,2,1,2,3], K = 2))
print(s.subarraysWithKDistinct(A = [1,2,1,3,4], K = 3))

在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 j<len(A) and len(d)<=K:
                    d[A[j]]+=1
                    j+=1
                    if len(d)<=K: res+=j-i
                while i<len(A) and len(d)>K:
                    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)
    

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/86906740