992. K 个不同整数的子数组(双指针)

难度困难174

给定一个正整数数组 A,如果 A 的某个子数组中不同整数的个数恰好为 K,则称 A 的这个连续、不一定独立的子数组为好子数组

(例如,[1,2,3,1,2] 中有 3 个不同的整数:12,以及 3。)

返回 A 中好子数组的数目。

示例 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].

示例 2:

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

提示:

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

 对于 求取不同整数的个数恰好为 K的子数组数量 的问题,可以转换为求取: 不同整数的个数最大为 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);
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值