992. Subarrays with K Different Integers

LeetCode

link

HashTable, Two Pointers, Sliding Windows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// import java.util.*;
class Solution {
static int subarraysWithKDistinct(int[] A, int K) {
return atMostK(A, K) - atMostK(A, K - 1);
}

static int atMostK(int[] A, int K) {
int start = 0, end = 0;
int len = 0;
Map<Integer, Integer> map = new HashMap<>();

while (end < A.length) {
int endNum = A[end];
map.put(endNum, map.getOrDefault(endNum, 0) + 1);
end++;
while (map.size() > K) {
int startNum = A[start];
map.put(startNum, map.get(startNum) - 1);
if (map.get(startNum) == 0) {
map.remove(startNum);
}
start++;
}
len += end - start;
}
return len;
}
}
/*
public class MyClass {
public static void main(String[] args) {
int[] A = { 1, 2, 1, 2, 3 };
int K = 2;
System.out.println(Solution.subarraysWithKDistinct(A, K));
}
}*/

0%