0128.最长连续序列
方法一:HashSet
时间复杂度 $O(n)$,空间复杂度 $O(n)$。
impl Solution {
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let mut set = std::collections::HashSet::new();
for (_, &num) in nums.iter().enumerate() {
set.insert(num);
}
let mut longest = 0;
for num in nums {
if !set.contains(&(num - 1)) {
let mut current = num;
let mut current_longest = 1;
while set.contains(&(current + 1)) {
current += 1;
current_longest += 1;
}
longest = std::cmp::max(longest, current_longest);
}
}
longest
}
}