-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlongestConsecutive.cpp
More file actions
103 lines (95 loc) · 2.69 KB
/
longestConsecutive.cpp
File metadata and controls
103 lines (95 loc) · 2.69 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
#include <vector>
#include <unordered_map>
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]);
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;
}
};
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
UnionFind uf(nums);
unordered_map<int, int> map; // father -> nums
for(int i = 0; i < nums.size(); i++){
int father = uf.find(nums[i]);
if(map.find(father) == map.end()){
map[father] = 1;
}
else{
map[father] = map[father] + 1;
}
}
int len = 0;
for(auto it = map.begin(); it != map.end(); it++){
len = max(len, it->second);
}
return len;
}
};
int main(void){
Solution sol;
vector<int> A = {0, 1};
cout << sol.longestConsecutive(A)<<endl;
return 0;
}