Преглед на файлове

feat: longest_consecutive_sequence

Zhang Li преди 11 месеца
родител
ревизия
04c2c6fc11
променени са 2 файла, в които са добавени 53 реда и са изтрити 1 реда
  1. 51 0
      src/solutions/array/longest_consecutive_sequence.rs
  2. 2 1
      src/solutions/array/mod.rs

+ 51 - 0
src/solutions/array/longest_consecutive_sequence.rs

@@ -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);
+    }
+}

+ 2 - 1
src/solutions/array/mod.rs

@@ -10,4 +10,5 @@ mod remove_duplicate_from_sorted_array2;
 mod merge_sorted_array;
 mod pascal_triangle;
 mod pascal_triangle2;
-mod triangle;
+mod triangle;
+mod longest_consecutive_sequence;