-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path128.cpp
More file actions
52 lines (48 loc) · 1.04 KB
/
128.cpp
File metadata and controls
52 lines (48 loc) · 1.04 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
/*
class Solution
{
public:
int longestConsecutive(vector<int>& nums)
{
unordered_map<int, int> dp;
int ret = 0;
for(auto &x : nums)
{
if(!dp[x])
dp[x - dp[x - 1]] = dp[x + dp[x + 1]] = dp[x] = dp[x - 1] + dp[x + 1] + 1;
ret = max(ret, dp[x]);
}
return ret;
}
};
*/
class Solution
{
public:
unordered_map<int, int> F;
int father(int x)
{
if(F.count(x) == 0)
return x;
if(F[x] != x)
F[x] = father(F[x]);
return F[x];
}
int longestConsecutive(vector<int>& nums)
{
F.clear();
for(auto x : nums)
{
F[x] = father(x);
if(F.count(x - 1) > 0)
F[father(x - 1)] = father(x);
if(F.count(x + 1) > 0)
F[father(x)] = father(x + 1);
}
int res = 0;
for(auto x : nums)
if(father(x) - x + 1 > res)
res = father(x) - x + 1;
return res;
}
};