-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSequence.cpp
More file actions
110 lines (98 loc) · 1.93 KB
/
Copy pathLongestConsecutiveSequence.cpp
File metadata and controls
110 lines (98 loc) · 1.93 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
#include <iostream>
#include <unordered_set>
using namespace std;
void display(vector<int> &arr)
{
for(auto x : arr)
{
cout << x << ' ';
}
cout << endl;
}
bool linearSearch(int n, vector<int> &arr)
{
for(int i=0; i<arr.size(); i++)
{
if(arr[i] == n)
{
return true;
}
}
return false;
}
int longestConsecutiveSequence1(vector<int> &arr)
{
int longestLen = 1;
int n = arr.size();
for(int i=0; i<n; i++)
{
vector<int> sequence;
int a = arr[i];
int currLen = 1;
while(linearSearch(a+1, arr) == true)
{
currLen++;
a++;
}
if(currLen > longestLen)
{
longestLen = currLen;
}
}
return longestLen;
}
int longestConsecutiveSequence2(vector<int> &arr)
{
int n = arr.size();
int maxLen = 1;
int currLen = 0, lastEle = INT_MIN;
sort(arr.begin(),arr.end());
for(int i=0; i<n; i++)
{
if(lastEle == arr[i]-1)
{
currLen++;
lastEle = arr[i];
}
else if(arr[i] != lastEle)
{
currLen = 1;
lastEle = arr[i];
}
maxLen = max(maxLen, currLen);
}
return maxLen;
}
int longestConsecutiveSequence3(vector<int> &arr)
{
int n = arr.size();
int maxLen = 1;
int currLen = 0;
unordered_set<int> s;
for(int i=0; i<n; i++)
{
s.insert(arr[i]);
}
for(auto a : s)
{
if(s.find(a-1) == s.end())
{
currLen = 1;
int x = a;
while(s.find(x+1) != s.end())
{
x++;
currLen++;
}
}
maxLen = max(currLen, maxLen);
}
return maxLen;
}
int main()
{
vector<int> arr = {102,4,100,1,101,3,2,1,1};
display(arr);
cout << longestConsecutiveSequence3(arr);
return 0;
}