Parcourir la source

feat: maximum_gap

Zhang Li il y a 11 mois
Parent
commit
8ad662dabe
2 fichiers modifiés avec 56 ajouts et 0 suppressions
  1. 55 0
      src/solutions/array/maximum_gap.rs
  2. 1 0
      src/solutions/array/mod.rs

+ 55 - 0
src/solutions/array/maximum_gap.rs

@@ -0,0 +1,55 @@
+struct Solution;
+impl Solution {
+    pub fn maximum_gap(nums: Vec<i32>) -> i32 {
+        let max = nums.iter().max().unwrap();
+        let min = nums.iter().min().unwrap();
+        if max == min { return 0; }
+        let n = nums.len();
+
+        let mut gap = (max - min) / (n as i32 -1);
+        if (max - min) % (n as i32 -1) != 0 {
+            gap += 1;
+        }
+        let mut min_bucket = vec![i32::MAX; n];
+        let mut max_bucket = vec![i32::MIN; n];
+        for i in 0..n {
+            let idx = ((nums[i] - min) / gap) as usize;
+            min_bucket[idx] = min_bucket[idx].min(nums[i]);
+            max_bucket[idx] = max_bucket[idx].max(nums[i]);
+        }
+
+        // println!("max_bucket: {:?}", max_bucket);
+        // println!("min_bucket: {:?}", min_bucket);
+
+        let mut res = i32::MIN;
+        let mut prev_max = i32::MIN;
+        for i in 0..n {
+            if min_bucket[i] == i32::MAX {
+                continue;
+            }
+
+            if prev_max == i32::MIN {
+                prev_max = max_bucket[i];
+                continue;
+            }
+
+            res = res.max(min_bucket[i] - prev_max);
+            prev_max = max_bucket[i];
+        }
+        res
+    }
+}
+
+
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_maximum_gap() {
+        let nums = vec![3,6,9,1,10];
+        let res = Solution::maximum_gap(nums);
+        assert_eq!(res, 3);
+    }
+}

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

@@ -15,3 +15,4 @@ mod longest_consecutive_sequence;
 mod longest_palindromic_substring;
 mod single_number;
 mod single_number2;
+mod maximum_gap;