Kaynağa Gözat

feat: find_minimum_in_rotated_array2

Zhang Li 11 ay önce
ebeveyn
işleme
db048a6096

+ 41 - 0
src/solutions/binary_search/find_minimum_in_rotated_array2.rs

@@ -0,0 +1,41 @@
+struct Solution;
+impl Solution {
+    pub fn find_min(nums: Vec<i32>) -> i32 {
+        Self::helper(&nums, 0, nums.len()-1)
+    }
+
+    fn helper(nums: &Vec<i32>, left: usize, right: usize) -> i32 {
+        if left == right { return nums[left]; }
+        if left + 1 == right { return nums[left].min(nums[right]); }
+        if nums[left] < nums[right] { return nums[left]; }
+        let mid = (left + right) / 2;
+        Self::helper(nums, left, mid).min(Self::helper(nums, mid+1, right))
+    }
+}
+
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_find_min() {
+        let nums = vec![3,4,5,1,2];
+        let res = Solution::find_min(nums);
+        assert_eq!(res, 1);
+    }
+
+    #[test]
+    fn test_find_min2() {
+        let nums = vec![3,3,3,3,3];
+        let res = Solution::find_min(nums);
+        assert_eq!(res, 3);
+    }
+
+    #[test]
+    fn test_find_min3() {
+        let nums = vec![2,2,2,0,1];
+        let res = Solution::find_min(nums);
+        assert_eq!(res, 0);
+    }
+}

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

@@ -7,4 +7,5 @@ mod search_in_rotated_sorted_array2;
 mod median_of_two_sorted_arrays;
 mod binary_tree_preorder_traversal;
 mod binary_tree_postorder_traversal;
-mod find_minimum_in_rotated_array;
+mod find_minimum_in_rotated_array;
+mod find_minimum_in_rotated_array2;