Browse Source

feat: search_in_rotated_sorted_array2

Zhang Li 1 year ago
parent
commit
891391b558

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

@@ -3,3 +3,4 @@ mod search_in_rotated_sorted_array;
 mod search_insert_position;
 mod sqrt;
 mod search_2d_matrix;
+mod search_in_rotated_sorted_array2;

+ 71 - 0
src/solutions/binary_search/search_in_rotated_sorted_array2.rs

@@ -0,0 +1,71 @@
+struct Solution;
+
+
+impl Solution {
+    pub fn search(nums: Vec<i32>, target: i32) -> bool {
+        let (mut left, mut right) = (0, nums.len()-1);
+
+        while left <= right {
+            let mid = (left + right) / 2;
+            if nums[mid] == target {
+                return true;
+            }
+
+            if nums[mid] == nums[left] {
+                left += 1;
+                continue;
+            }
+
+            if nums[left] <= nums[mid] {
+                if nums[left] <= target && target <= nums[mid] {
+                    if mid == 0 {
+                        return false;
+                    }
+                    right = mid - 1;
+
+                } else {
+                    left = mid + 1;
+                }
+                continue;
+            }
+
+            if nums[mid] <= nums[right] {
+                if nums[mid] <= target && target <= nums[right] {
+                    left = mid + 1;
+                } else {
+                    if mid == 0 {
+                        return false;
+                    }
+                    right = mid -1;
+                }
+                continue;
+            }
+        }
+
+        false
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_search() {
+        let nums = vec![2,5,6,0,0,1,2];
+        let target = 0;
+        let res = Solution::search(nums, target);
+        assert_eq!(res, true);
+
+    }
+
+    #[test]
+    fn test_search2() {
+        let nums = vec![2,2,2,2];
+        let target = 2;
+        let res = Solution::search(nums, target);
+        assert_eq!(res, true);
+
+    }
+}