|
| 1 | +/** |
| 2 | + * [154] Find Minimum in Rotated Sorted Array II |
| 3 | + * |
| 4 | + * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. |
| 5 | + * |
| 6 | + * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). |
| 7 | + * |
| 8 | + * Find the minimum element. |
| 9 | + * |
| 10 | + * The array may contain duplicates. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * |
| 14 | + * |
| 15 | + * Input: [1,3,5] |
| 16 | + * Output: 1 |
| 17 | + * |
| 18 | + * Example 2: |
| 19 | + * |
| 20 | + * |
| 21 | + * Input: [2,2,2,0,1] |
| 22 | + * Output: 0 |
| 23 | + * |
| 24 | + * Note: |
| 25 | + * |
| 26 | + * |
| 27 | + * This is a follow up problem to <a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/">Find Minimum in Rotated Sorted Array</a>. |
| 28 | + * Would allow duplicates affect the run-time complexity? How and why? |
| 29 | + * |
| 30 | + * |
| 31 | + */ |
| 32 | +pub struct Solution {} |
| 33 | + |
| 34 | +// submission codes start here |
| 35 | + |
| 36 | +/* |
| 37 | + 针对无重复的做法, 只要二分搜索找折点即可: 假如 nums[mid] > nums[base] 那么转折点一定在右侧, 否则在左侧 |
| 38 | +
|
| 39 | + 但假如有重复, 就可能有 nums[mid] == nums[base], 这时就尴尬了, 无法确定转折点在左半部分还是右半部分 |
| 40 | +
|
| 41 | + 可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) |
| 42 | +
|
| 43 | + 但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 |
| 44 | + */ |
| 45 | +impl Solution { |
| 46 | + pub fn find_min(nums: Vec<i32>) -> i32 { |
| 47 | + let mut lo = 0; |
| 48 | + let mut hi = nums.len() - 1; |
| 49 | + let mut mid = 0; |
| 50 | + while lo < hi { |
| 51 | + mid = lo + (hi - lo) / 2; |
| 52 | + if (nums[mid] > nums[hi]) { |
| 53 | + lo = mid + 1; |
| 54 | + } else if (nums[mid] < nums[hi]) { |
| 55 | + hi = mid; |
| 56 | + } else { |
| 57 | + hi -= 1; |
| 58 | + } |
| 59 | + } |
| 60 | + return nums[lo] |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +// submission codes end |
| 65 | + |
| 66 | +#[cfg(test)] |
| 67 | +mod tests { |
| 68 | + use super::*; |
| 69 | + |
| 70 | + #[test] |
| 71 | + fn test_154() { |
| 72 | + assert_eq!(Solution::find_min(vec![1,2,2,2,2,2]), 1); |
| 73 | + assert_eq!(Solution::find_min(vec![1,3,3]), 1); |
| 74 | + assert_eq!(Solution::find_min(vec![3,1,3,3]), 1); |
| 75 | + } |
| 76 | +} |
0 commit comments