-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path128.LongestConsecutiveSequence.h
More file actions
148 lines (105 loc) · 3.38 KB
/
128.LongestConsecutiveSequence.h
File metadata and controls
148 lines (105 loc) · 3.38 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
bluepp
2014-06-12
2014-07-15
2014-12-10
2014-12-22
May the force be with me!
Problem: Longest Consecutive Sequence
Source: https://oj.leetcode.com/problems/longest-consecutive-sequence/
Notes:
Given an unsorted array of integers, find the length of the longest consecutive
elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
Solution: Update solution. This solution is from Peking2 (http://blog.sina.com.cn/s/blog_b9285de20101iqar.html).
This solution is much easier to understand.
*/
int longestConsecutive(vector<int>& nums) {
int ret = 0;
unordered_set<int> set(nums.begin(), nums.end());
for (auto p : nums) {
if (!set.count(p)) {
continue;
}
set.erase(p);
int prev = p-1, next = p+1;
while (set.count(prev)) {
set.erase(prev);
prev--;
}
while (set.count(next)) {
set.erase(next);
next++;
}
ret = max(ret, next-prev-1);
}
return ret;
}
/* another one */
int longestConsecutive(vector<int>& nums) {
int ret = 0;
unordered_map<int, int> map;
for (auto p : nums)
{
if (!map.count(p))
{
int l = map.count(p-1) ? map[p-1] : 0;
int r = map.count(p+1) ? map[p+1] : 0;
int sum = l+r+1;
map[p] = sum;
ret = max(ret, sum);
map[p-l] = sum;
map[p+r] = sum;
}
}
return ret;
}
/* 2016-06-26 , unordered_map */
int longestConsecutive(vector<int>& nums) {
int ret = 0;
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++)
{
map[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++)
{
int d = nums[i];
int n = 1;
map.erase(d);
while (map.find(++d) != map.end())
{
n++;
map.erase(d);
}
d = nums[i];
while (map.find(--d) != map.end())
{
n++;
map.erase(d);
}
ret = max(ret, n);
}
return ret;
}
int longestConsecutive(vector<int> &num) {
unordered_set<int> s;
int n = num.size();
for (int i = 0; i < n; i++)
s.insert(num[i]);
int res = 0;
for(int i = 0; i < n && !s.empty(); i++)
{
// if (s.find(num[i]) == s.end()) continue; 2014-12-10
int upper = num[i], lower = num[i];
while (s.find(upper+1) != s.end())
s.erase(upper++);
while (s.find(lower-1) != s.end())
s.erase(lower--);
res = max(res, upper-lower+1);
}
return res;
}