forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path128.longest-consecutive-sequence.cpp
96 lines (74 loc) · 1.96 KB
/
128.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
84
85
86
87
88
89
90
91
92
93
94
95
96
class UnionFind {
private:
vector<int> table;
public:
UnionFind(int n){
table = vector<int>(n);
for (auto i = 0; i < n; ++i){
table[i] = i;
}
}
int find(int x){
if (table[x] == x){
return x;
}
return table[x] = find(table[x]);
}
void connect(int x, int y){
int superX = find(x);
int superY = find(y);
if (superX != superY){
table[superX] = superY;
}
}
int maxconnect(){
unordered_map<int, int> map;
int ans = 0;
for (auto i = 0; i < table.size(); ++i){
map[find(i)] += 1;
ans = max(ans, map[table[i]]);
}
return ans;
}
};
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> map;
for (auto i = 0; i < nums.size(); ++i){
map[nums[i]] = i;
}
UnionFind uf = UnionFind(nums.size());
for (auto i = 0; i < nums.size(); ++i){
int num = nums[i];
if (map[num] != i) {
continue;
}
if (map.count(num - 1) > 0){
uf.connect(i, map[num - 1]);
}
}
return uf.maxconnect();
}
int longestConsecutive2(vector<int>& nums) {
unordered_set<int> set;
for(auto n: nums){
set.insert(n);
}
int longest = 0;
for (auto n: set){
// has a previous small head
if (set.count(n - 1) > 0){
continue;
}
int currentNum = n;
int length = 1;
while (set.count(currentNum + 1) > 0){
currentNum += 1;
length += 1;
}
longest = max(length, longest);
}
return longest;
}
};