-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_consecutive_sequence.rs
51 lines (42 loc) · 1.28 KB
/
longest_consecutive_sequence.rs
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
#![allow(dead_code)]
use std::{collections::HashSet, iter::FromIterator};
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let set: HashSet<i32> = HashSet::from_iter(nums.into_iter());
let mut max = 0;
for n in &set {
if !set.contains(&(n - 1)) {
let mut next = n + 1;
let mut count = 1;
while set.contains(&next) {
count += 1;
next += 1;
}
max = max.max(count);
}
}
max
}
/*
Algorithm - HashSet
- Create a hashset from the given vector
- Iterate through the hashset
- If the current element - 1 is not in the hashset
- Create a counter and set it to 1
- Create a next variable and set it to current element + 1
- While the next variable is in the hashset
- Increment the counter
- Increment the next variable
- Set the max counter to the max of the current max counter and the counter
- Return the max counter
Time: O(n)
Space: O(n)
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_128() {
assert_eq!(longest_consecutive(vec![100, 4, 200, 1, 3, 2]), 4);
assert_eq!(longest_consecutive(vec![0, 3, 7, 2, 5, 8, 4, 6, 0, 1]), 9);
}
}