LeetCode Daily Question 992. Sub-arrays of K Different Integers

992. Sub-array of K distinct integers

Given a positive integer array A, if Athe array in a different sub-integer number exactly K, called Athis continuous, independent sub-array is not necessarily a good sub-array .

(E.g., [1,2,3,1,2]there are 3different 1integers: , 2, and 3.)

Returns the Anumber of good sub-array.

Example 1:

输入:A = [1,2,1,2,3], K = 2
输出:7
解释:恰好由 2 个不同整数组成的子数组:[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:

输入:A = [1,2,1,3,4], K = 3
输出:3
解释:恰好由 3 个不同整数组成的子数组:[1,2,1,3], [2,1,3], [1,3,4].

prompt:

  • 1 <= A.length <= 20000
  • 1 <= A[i] <= A.length
  • 1 <= K <= A.length

Method one: sliding window

Problem-solving ideas

The old rule is to simulate a "sliding window" with two pointers.

This question is a different way of thinking, find "the number of sub-arrays containing up to K different integers" and "the fraction of sub-arrays containing up to K-1 different integers", subtracting the two is "sub-arrays of K different integers" Number".

Reference Code

public int subarraysWithKDistinct(int[] A, int K) {
    
    
    return atMostK(A, K) - atMostK(A, K - 1);
}


public int atMostK(int[] A, int K) {
    
    
    int n = A.length;
    int[] counts = new int[n + 1];

    int count = 0;
    int ret = 0;
    int left = 0, right = 0;
    while (right < n) {
    
    
        if (counts[A[right]] == 0) {
    
    
            count++;
        }
        counts[A[right]]++;
        right++;

        while (count > K) {
    
    
            counts[A[left]]--;
            if (counts[A[left]] == 0) {
    
    
                count--;
            }
            left++;
        }
        ret += right - left;
    }
    return ret;
}

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113768185