瀏覽代碼

feat: find_minimum_in_rotated_array

Zhang Li 11 月之前
父節點
當前提交
5e1006d91b
共有 2 個文件被更改,包括 39 次插入1 次删除
  1. 37 0
      src/solutions/binary_search/find_minimum_in_rotated_array.rs
  2. 2 1
      src/solutions/binary_search/mod.rs

+ 37 - 0
src/solutions/binary_search/find_minimum_in_rotated_array.rs

@@ -0,0 +1,37 @@
+struct Solution;
+
+impl Solution {
+    pub fn find_min(nums: Vec<i32>) -> i32 {
+        Self::helper(&nums, 0, nums.len() -1)
+    }
+
+    fn helper(nums: &Vec<i32>, s: usize, e: usize) -> i32 {
+        if s == e { return nums[s]; }
+        if s + 1 == e { return nums[s].min(nums[e]); }
+
+        if nums[s] < nums[e] { return nums[s]; }
+
+        let mid = (s + e) / 2;
+        if nums[mid] > nums[e] {
+            return Self::helper(nums, mid, e);
+        }
+
+        if nums[s] > nums[mid] {
+            return Self::helper(nums, s, mid);
+        }
+
+        0
+    }
+}
+
+#[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);
+    }
+}

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

@@ -6,4 +6,5 @@ mod search_2d_matrix;
 mod search_in_rotated_sorted_array2;
 mod median_of_two_sorted_arrays;
 mod binary_tree_preorder_traversal;
-mod binary_tree_postorder_traversal;
+mod binary_tree_postorder_traversal;
+mod find_minimum_in_rotated_array;