From b6a938460310926b027abf09d920557997049e55 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 12 May 2024 10:48:36 +0800 Subject: [PATCH] 20240512 Finished --- src/problem/mod.rs | 3 +- .../p128_longest_consecutive_sequence.rs | 38 +++++++++++++++++++ src/problem/p49_group_anagrams.rs | 15 -------- 3 files changed, 40 insertions(+), 16 deletions(-) create mode 100644 src/problem/p128_longest_consecutive_sequence.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 7b7aa3f..164079f 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -128,4 +128,5 @@ mod p205_isomorphic_strings; mod p242_valid_anagram; mod p49_group_anagrams; mod p202_happy_number; -mod p219_contains_duplicate_ii; \ No newline at end of file +mod p219_contains_duplicate_ii; +mod p128_longest_consecutive_sequence; \ No newline at end of file diff --git a/src/problem/p128_longest_consecutive_sequence.rs b/src/problem/p128_longest_consecutive_sequence.rs new file mode 100644 index 0000000..2bf2731 --- /dev/null +++ b/src/problem/p128_longest_consecutive_sequence.rs @@ -0,0 +1,38 @@ +/** + * [128] Longest Consecutive Sequence + */ +pub struct Solution {} + +// submission codes start here +use std::collections::HashSet; + +impl Solution { + pub fn longest_consecutive(nums: Vec) -> i32 { + let d: HashSet = nums.iter().map(|&i| i).collect(); + nums.into_iter() + .map(|mut i| { + let mut t = 1; + if !d.contains(&(i - 1)) { + while d.contains(&(i + 1)) { + t += 1; + i += 1; + } + } + t + }) + .max() + .unwrap_or(0) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_128() { + assert_eq!(4, Solution::longest_consecutive(vec![100, 1, 200, 4, 3, 2])); + } +} diff --git a/src/problem/p49_group_anagrams.rs b/src/problem/p49_group_anagrams.rs index 02d4540..3f344c8 100644 --- a/src/problem/p49_group_anagrams.rs +++ b/src/problem/p49_group_anagrams.rs @@ -88,20 +88,5 @@ mod tests { characters: HashMap::from([('a', 1), ('t', 1), ('e', 1)]) } ); - assert_eq!( - vec![ - vec!["bat".to_owned()], - vec!["nat".to_owned(), "tan".to_owned()], - vec!["ate".to_owned(), "eat".to_owned(), "tea".to_owned()] - ], - Solution::group_anagrams(vec![ - "eat".to_owned(), - "tea".to_owned(), - "tan".to_owned(), - "ate".to_owned(), - "nat".to_owned(), - "bat".to_owned() - ]) - ); } }