-
Notifications
You must be signed in to change notification settings - Fork 3
/
longest_consecutive_sequence.cpp
83 lines (76 loc) · 2.09 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
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class UnionFind {
public:
unordered_map<int, int> father;
UnionFind(vector<int>& nums){
for(int i = 0; i < nums.size(); i++){
father[nums[i]] = nums[i]; // plus one
father[nums[i]+1] = nums[i]+1;
}
}
// find the super father of x
int find(int x) {
int parent = father.at(x);
while(parent != father.at(parent)){
parent = father.at(parent);
}
return parent;
}
int compressed_find(int x){
int parent = father.at(x);
while(parent != father.at(parent)){
parent = father.at(parent);
}
//带路径压缩的find
int fa = father.at(x);
while(fa != father.at(fa)){
int tmp = father.at(fa);
father.at(fa) = parent;
fa = tmp;
}
return parent;
}
int union_both(int x, int y) {
int fa_x = compressed_find(x);
int fa_y = compressed_find(y);
if(fa_x != fa_y) {
father.at(fa_x) = fa_y;
}
}
};
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
UnionFind uf(nums);
for(int i = 0; i < nums.size(); i++){
uf.union_both(nums[i], nums[i]+1);
}
unordered_map<int, unordered_set<int> > map; // father -> nums
for(int i = 0; i < nums.size(); i++){
int father = uf.find(nums[i]);
cout<<nums[i]<<" 's father is "<<father<<endl;
if(map.find(father) == map.end()){
unordered_set<int> set = {nums[i]};
map[father] = set;
}
else{
map[father].insert(nums[i]);
}
}
int len = 0;
for(auto it = map.begin(); it != map.end(); it++){
len = max(len, (int)(it->second.size()));
}
return len;
}
};
int main(void){
vector<int> A = {0, 2, 9, 1};
Solution sol;
cout << sol.longestConsecutive(A)<<endl;
return 0;
}