Skip to content

Commit a79f2a0

Browse files
authored
Update Subarrays with K Different Integers.java
1 parent 52cbe7e commit a79f2a0

File tree

1 file changed

+19
-25
lines changed

1 file changed

+19
-25
lines changed
Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
11
class Solution {
2-
public int subarraysWithKDistinct(int[] A, int K) {
3-
return atMostK(A, K) - atMostK(A, K - 1);
4-
}
5-
6-
private int atMostK(int[] A, int K) {
7-
int start = 0;
8-
int end = 0;
9-
int n = A.length;
10-
Map<Integer, Integer> map = new HashMap<>();
11-
int count = 0;
12-
while (end < n) {
13-
if (map.getOrDefault(A[end], 0) == 0) {
14-
K--;
15-
}
16-
map.put(A[end], map.getOrDefault(A[end], 0) + 1);
17-
while (K < 0) {
18-
map.put(A[start], map.getOrDefault(A[start], 0) - 1);
19-
if (map.get(A[start]) == 0) {
20-
K++;
2+
public int subarraysWithKDistinct(int[] nums, int k) {
3+
return slidingWindowAtMost(nums, k) - slidingWindowAtMost(nums, k - 1);
4+
}
5+
6+
private int slidingWindowAtMost(int[] nums, int k) {
7+
Map<Integer, Integer> map = new HashMap<>();
8+
int left = 0;
9+
int count = 0;
10+
for (int right = 0; right < nums.length; right++) {
11+
map.put(nums[right], map.getOrDefault(nums[right], 0) + 1);
12+
while (map.size() > k) {
13+
map.put(nums[left], map.get(nums[left]) - 1);
14+
if (map.get(nums[left]) == 0) {
15+
map.remove(nums[left]);
16+
}
17+
left++;
18+
}
19+
count += right - left + 1;
2120
}
22-
start++;
23-
}
24-
count += end - start + 1;
25-
end++;
21+
return count;
2622
}
27-
return count;
28-
}
2923
}

0 commit comments

Comments
 (0)