992. Sub-array of K different integers (double pointer)

Difficulty 174

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

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

Returns  the number A of good sub-arrays .

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. 1 <= A.length <= 20000
  2. 1 <= A[i] <= A.length
  3. 1 <= K <= A.length

 For obtaining the number of different integers exactly  K的子数组数量 的问题,可以转换为求取: different integer number up to  different maximum number of integer K的子数组数量 减去 K-1的子数组数量,因此通过滑动窗判断即可得出两种情况的子数组数量和,相减即为结果。

 

class Solution {
private:
	int room[20001];
	int subarrayswithmax(vector<int>& A, int K) {
		memset(room, 0, sizeof(room));
		int left = 0, right = 0;
		int count = 0;
		int res = 0;
		while (right < A.size()) {
			if (room[A[right]] == 0) {
				count++;
			}
			room[A[right]]++;
			right++;
			while (count > K) {
				room[A[left]]--;
				if (room[A[left]] == 0) {
					count--;
				}
				left++;
			}
			res += right - left;
		}
		return res;
	}
public:
	int subarraysWithKDistinct(vector<int>& A, int K) {
		
		return subarrayswithmax(A,K) - subarrayswithmax(A, K - 1);
	}
};

 

Guess you like

Origin blog.csdn.net/Yanpr919/article/details/113769424