-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq659
More file actions
38 lines (36 loc) · 1.29 KB
/
q659
File metadata and controls
38 lines (36 loc) · 1.29 KB
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
37
38
class Solution {
public boolean isPossible(int[] nums) {
// idea from lee215's post
// https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/106514/Python-Easy-Understand-Greedy
Map<Integer, Integer> m1 = new HashMap<>(), m2 = new HashMap<>();
for(int k : nums)
{
m1.put(k, m1.getOrDefault(k, 0) + 1);
}
for(int k : nums)
{
if(!m1.containsKey(k)) continue;
m1.put(k, m1.get(k) - 1);
if(m1.get(k) == 0) m1.remove(k);
if(m2.containsKey(k - 1))
{
m2.put(k - 1, m2.get(k - 1) - 1);
if(m2.get(k - 1) == 0) m2.remove(k - 1);
m2.put(k, m2.getOrDefault(k, 0) + 1);
}
else
{
if(m1.containsKey(k + 1) && m1.containsKey(k + 2))
{
m1.put(k + 1, m1.get(k + 1) - 1);
if(m1.get(k + 1) == 0) m1.remove(k + 1);
m1.put(k + 2, m1.get(k + 2) - 1);
if(m1.get(k + 2) == 0) m1.remove(k + 2);
m2.put(k + 2, m2.getOrDefault(k + 2, 0) + 1);
}
else return false;
}
}
return true;
}
}