Skip to content

Commit 3c68196

Browse files
committed
Add the solution for LC #2537
1 parent 6d516e9 commit 3c68196

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package org.sean.array;
2+
3+
import java.util.HashMap;
4+
5+
/***
6+
* 2537. Count the Number of Good Subarrays
7+
*/
8+
public class GoodSubarrayCounter {
9+
public long countGood(int[] nums, int k) {
10+
int len = nums.length;
11+
int left = 0, right = 0;
12+
13+
int currPairCnt = 0;
14+
long res = 0L;
15+
HashMap<Integer, Integer> map = new HashMap<>();
16+
17+
while (left < len && right < len) {
18+
while (right < len) {
19+
int elem = nums[right];
20+
21+
if (map.containsKey(elem)) {
22+
int cnt = map.get(elem);
23+
currPairCnt += cnt;
24+
map.put(elem, cnt + 1);
25+
} else {
26+
map.put(elem, 1);
27+
}
28+
if (currPairCnt >= k) {
29+
int add = len - right;
30+
res += add;
31+
// System.out.printf("%d matched substring found, range from %d to %d\n", add, left, right);
32+
break;
33+
}
34+
35+
right++;
36+
}
37+
38+
while (currPairCnt >= k && left < right) {
39+
int leftElem = nums[left];
40+
int leftCnt = map.getOrDefault(leftElem, 0);
41+
42+
// relax from left side
43+
map.put(leftElem, leftCnt - 1);
44+
if (leftCnt == 1)
45+
map.remove(leftElem);
46+
47+
currPairCnt -= leftCnt - 1; // the num of increased pairs
48+
left++;
49+
50+
if (currPairCnt >= k) {
51+
// System.out.printf("matched substring found, range from %d to %d\n", left, right);
52+
// [left', right...]
53+
res += len - right;
54+
}
55+
}
56+
57+
// advance the right pointer
58+
right++;
59+
}
60+
61+
return res;
62+
}
63+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.sean.array;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
public class GoodSubarrayCounterTest {
9+
10+
private GoodSubarrayCounter counter;
11+
12+
@Before
13+
public void setUp() throws Exception {
14+
counter = new GoodSubarrayCounter();
15+
}
16+
17+
@Test
18+
public void countGood() {
19+
long ans = counter.countGood(new int[]{3, 1, 4, 3, 2, 2, 4, 3, 1, 4, 3, 2}, 2);
20+
assertEquals(31, ans);
21+
}
22+
}

0 commit comments

Comments
 (0)