-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest-consecutive-sequence.cpp
70 lines (62 loc) · 1.58 KB
/
longest-consecutive-sequence.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class MiniSet {
public:
bool inSet(int x){
return repTable.count(x) > 0 ? true : false;
}
void makeSet(int x) {
if (repTable.count(x) == 0)
repTable[x] = {x, 0};
}
int findSet(int x) {
int &xRep = repTable[x].first;
if (x != xRep){
xRep = findSet(xRep);
}
return xRep;
}
void merge(int x, int y) {
link(findSet(x), findSet(y));
}
int getMostFrequency(){
int maxFre = numeric_limits<int>::min();
for (auto &info : repTable){
setCount[findSet(info.first)]++;
}
for (auto &xf: setCount){
maxFre = max(maxFre, xf.second);
}
return maxFre;
}
private:
unordered_map<int, pair<int, int> > repTable;
unordered_map<int, int> setCount;
void link(int x, int y) {
int &xrank = repTable[x].second;
int &yrank = repTable[y].second;
if (xrank > yrank){
repTable[y].first = x;
}
else {
repTable[x].first = y;
if (xrank == yrank) yrank++;
}
}
};
class Solution {
public:
int longestConsecutive(vector<int> &num) {
MiniSet ms;
for (int x : num){
ms.makeSet(x);
}
for (int x : num){
if (ms.inSet(x-1)){
ms.merge(x, x-1);
}
if (ms.inSet(x+1)){
ms.merge(x, x+1);
}
}
return ms.getMostFrequency();
}
};