diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6bf642c..a4cd878 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -175,4 +175,5 @@ mod p108_convert_sorted_array_to_binary_search_tree; mod p53_maximum_subarray; mod p918_maximum_sum_circular_subarray; mod p35_search_insert_position; -mod p74_search_a_2d_matrix; \ No newline at end of file +mod p74_search_a_2d_matrix; +mod p33_search_in_rotated_sorted_array; \ No newline at end of file diff --git a/src/problem/p33_search_in_rotated_sorted_array.rs b/src/problem/p33_search_in_rotated_sorted_array.rs new file mode 100644 index 0000000..e0b05ff --- /dev/null +++ b/src/problem/p33_search_in_rotated_sorted_array.rs @@ -0,0 +1,58 @@ +/** + * [33] Search in Rotated Sorted Array + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn search(nums: Vec, target: i32) -> i32 { + if nums.len() == 1 { + return if target == nums[0] { + 0 + } else { + -1 + }; + } + + let (mut left, mut right) = (0, nums.len()); + + while left < right { + let middle = (right - left) / 2 + left; + + if nums[middle] == target { + return middle as i32; + } + + if nums[middle] > nums[0] { + // 左侧的数组是有序的 + if target >= nums[0] && target < nums[middle] { + right = middle; + } else { + left = middle + 1; + } + } else { + // 右侧数组是有序的 + if target > nums[middle] && target <= nums[nums.len() - 1] { + left = middle + 1; + } else { + right = middle; + } + } + } + + -1 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_33() { + } +}