Likou 992.K sub-array of different integers-C language implementation

topic

Link
to the original question Given a positive integer array A, if the number of different integers in a sub-array of A happens to be K, then this continuous, not necessarily independent sub-array of A is called a good sub-array.

(For example, there are 3 different integers in [1,2,3,1,2]: 1, 2, and 3.)

Returns the number of good sub-arrays in A.

Example 1:

Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: A sub-array consisting of 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: A sub-array consisting of exactly 3 different integers: [1,2,1,3], [2,1, 3], [1,3,4].

prompt:

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

Problem solving

What we require is the number of consecutive sub-arrays that happen to consist of k types of integers in array A.
Analysis:
k kinds of integers, so at least the length is k and
requires continuous

This kind of requirement feels that you can use double pointers
to traverse from the beginning, the left is marked as left, and the right is marked as right.
What we often get through double pointers is the largest and largest problems, here is exactly equal to k, so the conversion is to use The number of sub-arrays with a maximum of k different integers can be obtained by subtracting the number of sub-arrays with a maximum of k-1 different integers.

template:

int subarraysWithKDistinct(int* A, int ASize, int K){
    
    
  
}

Solution to a problem link - Author: LeetCode-Solution

int subarraysWithKDistinct(int* A, int ASize, int K) {
    
    
    int num1[ASize + 1], num2[ASize + 1];
    memset(num1, 0, sizeof(int) * (ASize + 1));
    memset(num2, 0, sizeof(int) * (ASize + 1));
    int tot1 = 0, tot2 = 0;
    int left1 = 0, left2 = 0, right = 0;
    int ret = 0;
    while (right < ASize) {
    
    
        if (!num1[A[right]]) {
    
    
            tot1++;
        }
        num1[A[right]]++;
        if (!num2[A[right]]) {
    
    
            tot2++;
        }
        num2[A[right]]++;
        while (tot1 > K) {
    
    
            num1[A[left1]]--;
            if (!num1[A[left1]]) {
    
    
                tot1--;
            }
            left1++;
        }
        while (tot2 > K - 1) {
    
    
            num2[A[left2]]--;
            if (!num2[A[left2]]) {
    
    
                tot2--;
            }
            left2++;
        }
        ret += left2 - left1;
        right++;
    }
    return ret;
}

Guess you like

Origin blog.csdn.net/qq_44922487/article/details/113765557