|
| 1 | +/// @number 33 |
| 2 | +/// @title Search in Rotated Sorted Array |
| 3 | +/// @url https://leetcode.com/problems/search-in-rotated-sorted-array/ |
| 4 | +/// @difficulty Medium |
| 5 | +
|
| 6 | +struct Solution; |
| 7 | + |
| 8 | +impl Solution { |
| 9 | + pub fn rotated_index(nums: &Vec<i32>, start: usize, end: usize) -> usize { |
| 10 | + if nums[start] < nums[end] { |
| 11 | + start |
| 12 | + } else { |
| 13 | + let mid = (end + start) / 2; |
| 14 | + if mid == start { |
| 15 | + return mid; |
| 16 | + } |
| 17 | + if nums[mid] < nums[start] { |
| 18 | + Solution::rotated_index(nums, start, mid) |
| 19 | + } else { |
| 20 | + Solution::rotated_index(nums, mid, end) |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + pub fn search(nums: Vec<i32>, target: i32) -> i32 { |
| 26 | + if nums.len() == 0 { |
| 27 | + return -1; |
| 28 | + } |
| 29 | + |
| 30 | + let rotated_index = Solution::rotated_index(&nums, 0, nums.len() - 1); |
| 31 | + |
| 32 | + let index = if nums[0] <= target && target <= nums[rotated_index] { |
| 33 | + nums[0..=rotated_index].binary_search(&target) |
| 34 | + } else if rotated_index < nums.len() - 1 { |
| 35 | + if nums[rotated_index + 1] <= target && target <= nums[nums.len() - 1] { |
| 36 | + nums[rotated_index..nums.len()] |
| 37 | + .binary_search(&target) |
| 38 | + .map(|i| i + rotated_index) |
| 39 | + } else { |
| 40 | + Err(0) |
| 41 | + } |
| 42 | + } else { |
| 43 | + Err(0) |
| 44 | + }; |
| 45 | + |
| 46 | + if let Ok(index) = index { |
| 47 | + index as i32 |
| 48 | + } else { |
| 49 | + -1 |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +#[cfg(test)] |
| 55 | +mod test { |
| 56 | + use crate::search_in_rotated_sorted_array::Solution; |
| 57 | + |
| 58 | + #[test] |
| 59 | + fn test_rotated() { |
| 60 | + assert_eq!(3, Solution::rotated_index(&vec![4, 5, 6, 7, 0, 1, 2], 0, 6)) |
| 61 | + } |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn test() { |
| 65 | + assert_eq!(4, Solution::search(vec![4, 5, 6, 7, 0, 1, 2], 0)); |
| 66 | + } |
| 67 | + |
| 68 | + #[test] |
| 69 | + fn test2() { |
| 70 | + assert_eq!(-1, Solution::search(vec![4, 5, 6, 7, 0, 1, 2], 3)); |
| 71 | + } |
| 72 | + |
| 73 | + #[test] |
| 74 | + fn test3() { |
| 75 | + assert_eq!(7, Solution::search(vec![4, 5, 6, 7, 0, 1, 2, 3], 3)); |
| 76 | + } |
| 77 | + #[test] |
| 78 | + fn test4() { |
| 79 | + assert_eq!(-1, Solution::search(vec![], 3)); |
| 80 | + } |
| 81 | + |
| 82 | + #[test] |
| 83 | + fn test5() { |
| 84 | + assert_eq!(-1, Solution::search(vec![1], 3)); |
| 85 | + } |
| 86 | + #[test] |
| 87 | + fn test6() { |
| 88 | + assert_eq!(0, Solution::search(vec![1], 1)); |
| 89 | + } |
| 90 | +} |
0 commit comments