Skip to content

Commit d4de3fd

Browse files
committed
'Longest Consecutive Sequence' soln
1 parent d43b4a7 commit d4de3fd

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
///
2+
/// Problem: Longest Consecutive Sequence
3+
///
4+
/// Given an unsorted array of integers nums, return the length of the longest consecutive
5+
/// elements sequence.
6+
///
7+
/// You must write an algorithm that runs in O(n) time.
8+
///
9+
/// Example 1:
10+
/// Input: nums = [100,4,200,1,3,2]
11+
/// Output: 4
12+
/// Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
13+
///
14+
/// Example 2:
15+
/// Input: nums = [0,3,7,2,5,8,4,6,0,1]
16+
/// Output: 9
17+
///
18+
/// Constraints:
19+
/// 0 <= nums.length <= 10^5
20+
/// -10^9 <= nums[i] <= 10^9
21+
///
22+
23+
// # Solution
24+
// Time complexity: O(n)
25+
// Space complexity: O(n)
26+
27+
use std::collections::HashSet;
28+
29+
impl Solution {
30+
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
31+
if nums.is_empty() {
32+
return 0;
33+
}
34+
35+
let num_set: HashSet<i32> = nums.into_iter().collect();
36+
37+
let mut max_length = 0;
38+
39+
for &num in &num_set {
40+
if !num_set.contains(&(num - 1)) {
41+
let mut current_num = num;
42+
let mut current_length = 1;
43+
44+
while num_set.contains(&(current_num + 1)) {
45+
current_num += 1;
46+
current_length += 1;
47+
}
48+
49+
max_length = max_length.max(current_length);
50+
}
51+
}
52+
53+
max_length
54+
}
55+
}

0 commit comments

Comments
 (0)