Skip to content

Commit a171ddf

Browse files
authored
2022-08-19 update: added "Split Array into Consecutive Subsequences" (#71)
1 parent 4adc51f commit a171ddf

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.PriorityQueue;
6+
import java.util.Queue;
7+
8+
// https://leetcode.com/problems/split-array-into-consecutive-subsequences/
9+
public class SplitArrayIntoConsecutiveSubsequences {
10+
11+
private final int[] input;
12+
13+
public SplitArrayIntoConsecutiveSubsequences(int[] input) {
14+
this.input = input;
15+
}
16+
17+
public boolean solution() {
18+
if (input.length < 3) {
19+
return false;
20+
}
21+
Map<Integer, Integer> m = new HashMap<>();
22+
for (int num : input) {
23+
m.put(num, m.getOrDefault(num, 0) + 1);
24+
}
25+
Queue<Integer> q = new PriorityQueue<>(m.keySet());
26+
while (!q.isEmpty()) {
27+
int min = q.peek();
28+
int count = 0;
29+
while (true) {
30+
if (!m.containsKey(min)) {
31+
if (count < 3) {
32+
return false;
33+
}
34+
break;
35+
}
36+
m.put(min, m.get(min) - 1);
37+
count++;
38+
if (m.get(min) == 0) {
39+
if (min != q.peek()) {
40+
return false;
41+
}
42+
q.poll();
43+
}
44+
if (m.containsKey(min + 1) && m.get(min) + 1 > m.get(min + 1)) {
45+
if (count < 3) {
46+
return false;
47+
}
48+
break;
49+
}
50+
min += 1;
51+
}
52+
}
53+
return true;
54+
}
55+
56+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertTrue;
6+
7+
public class SplitArrayIntoConsecutiveSubsequencesTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertTrue(new SplitArrayIntoConsecutiveSubsequences(new int[]{1, 2, 3, 3, 4, 5}).solution());
12+
}
13+
14+
}

0 commit comments

Comments
 (0)