|
@@ -0,0 +1,51 @@
|
|
|
|
+use std::collections::HashMap;
|
|
|
|
+
|
|
|
|
+struct Solution;
|
|
|
|
+impl Solution {
|
|
|
|
+ pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
|
|
|
|
+ if nums.is_empty() { return 0; }
|
|
|
|
+ let mut res = 1;
|
|
|
|
+ let mut m = HashMap::new();
|
|
|
|
+ for i in nums {
|
|
|
|
+ if m.contains_key(&i) { continue; }
|
|
|
|
+
|
|
|
|
+ let left = m.get(&(i-1)).unwrap_or(&0);
|
|
|
|
+
|
|
|
|
+ let right = m.get(&(i+1)).unwrap_or(&0);
|
|
|
|
+
|
|
|
|
+ let val = *left + *right + 1;
|
|
|
|
+ if val > res {
|
|
|
|
+ res = val;
|
|
|
|
+ }
|
|
|
|
+ let l_bound = i - *left;
|
|
|
|
+ let r_bound = i + *right;
|
|
|
|
+ m.insert(i, val);
|
|
|
|
+ m.insert(l_bound, val);
|
|
|
|
+ m.insert(r_bound, val);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ res
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+#[cfg(test)]
|
|
|
|
+mod tests {
|
|
|
|
+ use super::*;
|
|
|
|
+
|
|
|
|
+ #[test]
|
|
|
|
+ fn test_longest_consecutive() {
|
|
|
|
+ let nums = vec![100,4,200,1,3,2];
|
|
|
|
+
|
|
|
|
+ let res = Solution::longest_consecutive(nums);
|
|
|
|
+ assert_eq!(res, 4);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ #[test]
|
|
|
|
+ fn test_longest_consecutive2() {
|
|
|
|
+ let nums = vec![0,3,7,2,5,8,4,6,0,1];
|
|
|
|
+
|
|
|
|
+ let res = Solution::longest_consecutive(nums);
|
|
|
|
+ assert_eq!(res, 9);
|
|
|
|
+ }
|
|
|
|
+}
|