Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

992. Subarrays with K Different Integers

Posted on 2020-07-04 | Edited on 2021-01-22

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));
}
}*/

<1…858687…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%