-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_consecutive_sequence.cpp
65 lines (59 loc) · 1.71 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
// =====================================================================================
//
// Filename: longest_consecutive_sequence.cpp
//
// Description: 128. Longest Consecutive Sequence. Given an unsorted array of
// integers, find the length of the longest consecutive elements
// sequence. Your algorithm should run in O(n) complexity.
//
// Version: 1.0
// Created: 08/21/2019 09:09:21 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution
{
public:
int longestConsecutive(vector<int>& nums)
{
unordered_set<int> num_set(nums.begin(), nums.end());
int max_count = 0;
for (const auto& n: nums)
{
// Lower adjacent
int adjacent = n;
int cur_count = 0;
while (num_set.erase(adjacent) != 0)
{
cur_count++;
adjacent--;
}
// Upper adjacent
adjacent = n + 1;
while (num_set.erase(adjacent) != 0)
{
cur_count++;
adjacent++;
}
if (cur_count > max_count)
{
max_count = cur_count;
}
}
return max_count;
}
};
int main(int argc, char* argv[])
{
vector<int> nums = {100, 4, 200, 1, 3, 2};
int longest = Solution().longestConsecutive(nums);
printf("Longest consecutive sequence: %d\n", longest);
}