-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path128_longest_consecutive_sequence.cpp
More file actions
65 lines (51 loc) · 1.5 KB
/
128_longest_consecutive_sequence.cpp
File metadata and controls
65 lines (51 loc) · 1.5 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
/*
LeetCode 128 - Longest Consecutive Sequence
Difficulty: Medium
Problem:
Given an unsorted array of integers nums, return the length of the longest consecutive
elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Length = 4.
Example 2:
Input: nums = [0,3,7,2,5,8,1,6,0,4]
Output: 9
Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
Time Complexity: O(n)
Space Complexity: O(n)
*/
#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> num_set(nums.begin(), nums.end());
int longest = 0;
for (int num : num_set) {
// Only start counting from the beginning of a sequence
if (num_set.find(num - 1) == num_set.end()) {
int length = 1;
while (num_set.find(num + length) != num_set.end()) {
length++;
}
longest = max(longest, length);
}
}
return longest;
}
};
int main() {
Solution solution;
vector<int> nums1 = {100, 4, 200, 1, 3, 2};
cout << solution.longestConsecutive(nums1) << endl; // 4
vector<int> nums2 = {0, 3, 7, 2, 5, 8, 1, 6, 0, 4};
cout << solution.longestConsecutive(nums2) << endl; // 9
return 0;
}