Skip to content

Commit fde6890

Browse files
committed
largest cons seq
1 parent 089bbde commit fde6890

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Longest Consecutive Sequence
3+
============================
4+
5+
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
6+
7+
Example 1:
8+
Input: nums = [100,4,200,1,3,2]
9+
Output: 4
10+
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
11+
12+
Example 2:
13+
Input: nums = [0,3,7,2,5,8,4,6,0,1]
14+
Output: 9
15+
16+
Constraints:
17+
0 <= nums.length <= 104
18+
-109 <= nums[i] <= 109
19+
20+
Follow up: Could you implement the O(n) solution?
21+
*/
22+
23+
class Solution
24+
{
25+
public:
26+
int longestConsecutive(vector<int> &nums)
27+
{
28+
int n = nums.size();
29+
if (n <= 1)
30+
return n;
31+
32+
int ans = 1;
33+
unordered_set<int> s;
34+
for (auto &i : nums)
35+
s.insert(i);
36+
37+
for (auto &i : nums)
38+
{
39+
if (s.find(i - 1) != s.end())
40+
continue;
41+
int num = i;
42+
int count = 1;
43+
while (s.find(num + 1) != s.end())
44+
{
45+
count++;
46+
num = num + 1;
47+
}
48+
ans = max(ans, count);
49+
}
50+
return ans;
51+
}
52+
};

Striver Sheet/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
- [Two Sum](https://leetcode.com/problems/two-sum/) - [Cpp Soultion](./Day-4/Two%20Sum.cpp)
3535
- [4Sum](https://leetcode.com/problems/4sum/) - [Cpp Soultion](./Day-4/4Sum.cpp)
36-
- []() - [Cpp Soultion](./Day-4/.cpp)
36+
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) - [Cpp Soultion](./Day-4/Longest%20Consecutive%20Sequence.cpp)
3737
- []() - [Cpp Soultion](./Day-4/.cpp)
3838
- []() - [Cpp Soultion](./Day-4/.cpp)
3939
- []() - [Cpp Soultion](./Day-4/.cpp)

0 commit comments

Comments
 (0)