-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ20 -> Split Array into Consecutive Subsequences
45 lines (45 loc) · 1.36 KB
/
Q20 -> Split Array into Consecutive Subsequences
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
39
40
41
42
43
44
45
class Solution {
public:
class comparasion {
public:
bool operator()(pair<int, int>& a, pair<int, int>& b) {//always put the smallest and shortest sequence on the top of the heap
if(a.first == b.first) return a.second > b.second;
return a.first > b.first;
};
};
bool isPossible(vector<int>& nums) {
priority_queue<pair<int, int>, vector<pair<int, int>>, comparasion> qe;
int i = 0;
while(i < nums.size()) {
if(qe.empty()) {
qe.push({nums[i], 1});
i++;
}
else {
pair<int, int> tmp = qe.top();
if(nums[i] == tmp.first) {
qe.push({nums[i], 1});//add a new sequence
i++;
}
else if(nums[i] == tmp.first + 1) {
qe.pop();
qe.push({nums[i], tmp.second + 1});//update the top of the heap
i++;
}
else {
if(tmp.second < 3) {//false
return false;
}
qe.pop();
}
}
}
while(!qe.empty()) {
if(qe.top().second < 3) {
return false;
}
qe.pop();
}
return true;
}
};