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: 1, 2, 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].
解析:
网上很多算法我都看不懂,找了这种最容易懂的
恰好为K的 = 最多为k的数量 - 最多为k-1的数量
怎么算最多为k的数量?
统计数量时思路要清晰,j一直向右遍历的时候,找出以当前j结尾的,所有符合要求的情况
统计时关注两点:
- 要保证当前 i…j 窗口小于等于K, 是符合要求的
- 盯着这个当前j, 以j结尾的数量为i-j+1
public int subarraysWithKDistinct(int[] a, int k) {
return atMost(a, k) - atMost(a, k-1);
}
private int atMost(int[] a, int k) {//less or equal to
int i = 0, j =0;
Map<Integer, Integer> map = new HashMap();
int res = 0;
for(; j < a.length; j++) {
map.put(a[j], map.getOrDefault(a[j], 0) + 1);
while(map.size() > k) {// >k是不能算进去的,先把前面的i收缩到符合要求为止
int cur = map.get(a[i]);
if(cur == 1)
map.remove(a[i]);
else
map.put(a[i], cur-1);
i++;
}
res+= j-i+1;// 以j结尾的所有组合数是j-i+1
}
return res;
}